Bulls and cows - validating user's input of word length

Hi,

Did anybody here go for the optional challenge, letting the user decide the word length? How did you validate that choice?

My method kept getting completely thrown out of whack until I looked up cin.clear() and cin.ignore(1000,‘\n’) which weren’t in any of the lectures up until then and which I honestly still don’t entirely understand. Do you know an easier way?
(Also, does getline really not work with ints at all or is there something I’m missing?)
Thanks all!

int32 GetValidWordLength()
{
int32 LengthRequested = 0;
std::cout << "Tell me how long a word you’d like to try and guess [pick a number between 3 and 6]: ";

do {
std::cin>>LengthRequested;
if (!std::cin >> LengthRequested) {
std::cout << "Please just enter a number between 3 and 6: ";
std::cin.clear();
std::cin.ignore(1000, ‘\n’);
}
else if(LengthRequested < 3) {
std::cout << "I said a number between THREE and six: ";
}
else if (LengthRequested > 6) {
std::cout << "I said a number between three and SIX: ";
}
} while (LengthRequested < 3 || LengthRequested > 6);
std::cin.clear();
std::cin.ignore(1000, ‘\n’);
return LengthRequested;
}

No that’s probably the “best” way to do it. For std::getline you would then need to convert it to an int which is a bit more convoluted than it should be.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.