Search code examples
c++c-strings

How to only print the first word of a string in c++


How do I set this up to only read the first word the user enters IF they enter to much info?

I do not want to use an if-else statement demanding they enter new info because their info was to much.

I just want it to basically ignore everything after the first word and only print the first word entered. Is this even possible?

const int SIZEB = 10;
char word[SIZEB];
cout << " Provide a word, up to 10 characters, no spaces. > " << endl;
cin.getline(word, SIZEB);
cout << " The word is: " << word << endl;
cout << endl;

UPDATE

It HAS to be a cstring. This is something I am working on for school. I am asking a series of questions and storing the answers as cstring in the first round. Then there is a second round where I store them as string.


Solution

  • try this:

    const int SIZEB = 10;
    char word[SIZEB];
    cout << " Provide a word, up to 10 characters, no spaces. > " << endl;
    cin.getline(word, SIZEB);
    
    std::string input = word;
    std::string firstWord = input.substr(0, input.find(" "));
    
    cout << " The word is: " << firstWord << endl;
    cout << endl;
    

    You need to do:

    #include <string>