How to print only the first word of a line in C ++

How can I configure this to read only the first word that the user enters if they enter a lot of information?

I do not want to use the if-else statement, which requires entering new information, because there was a lot of their information.

I just want it to basically ignore everything after the first word and print only the first word entered. Is it 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 must be cstring. This is what I work at school. I ask a series of questions and save the answers as cstring in the first round. Then there is a second round where I store them as a string.

+4
source share
2 answers

try the following:

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>
+6
std::string word;
std::cout << "Provide a word, up to 10 characters, no spaces.";
std::cin >> word;

std::cout << "The word is: " << word;

10 , . , ..

" c". ...

char word[11] = {0}; // keep an extra byte for null termination
cin.getline(word, sizeof(word) - 1);

for(auto& c : word)
{
    // replace spaces will null
    if(c == ' ')
       c = 0;
}

cout << "The word is: " << word << endl;
+1

Source: https://habr.com/ru/post/1668571/


All Articles