简体   繁体   中英

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.

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

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

If you have to have it less than 10 characters, you can truncate the string as necessary. No reason for C-style strings, arrays etc.

"I have to use ac string." Sigh...

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;

you could also use this method:

std::string str;
std::cin >> str;
std::string word;
int str_size = str.size();
for(int i = 0; i < str_size; i++){
    word.push_back(str[i]);
    if(str[i] == ' ') break;
}
std::cout << "\n" << word << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM