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 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With