Hi this is the function I'm looking at below. The method works perfectly if you only enter integers as userChoice is an int. Although whenever I enter any other type it spams the console. How can I validate it against these other types?
1 2 3 4 5 6 7 8
void getUserChoice() {
do {
cout << "Enter choice: ";
cin >> userChoice;
if (userChoice <= 0 || userChoice > 5)
cout << "Please enter from 1-5!" << endl;
} while (userChoice <= 0 || userChoice > 5);
}
Ah thanks, I don't however understand this statement:
std::istringstream is {line};
if((is >> num) && !(is >> line)) //re-using `line` to test for extra stuff after the number
{
break; //done, we got what we wanted
}
The >> operator returns the stream, and streams are implicitly convertible to a boolean which lets you know if the stream is still in a valid state after the last operation. The code reads as "if reading into num succeeds and reading into line fails".