Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c-strings

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.

like image 920
Katie Stevers Avatar asked Feb 02 '17 01:02

Katie Stevers


2 Answers

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>
like image 159
Wagner Patriota Avatar answered Oct 09 '22 08:10

Wagner Patriota


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 a c 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;
like image 30
Chad Avatar answered Oct 09 '22 06:10

Chad