Super super beginner here! Trying out loops etc. See my code below. If the user enters a character, the program enters an infinite loop. Why? I know it's not the correct variable type, but surely it'd just put the ASCII code into the int variable?
Your cin is meant to accept ints, not strings or chars. Going against that puts cin into a fail state. Because of that your cin is not accepting any more prompts until that's fixed.
As Olysold said when you enter a char or string it put the stream (cin) into a error state because you variable is meant to accept int (whole numbers) only.
You will need to correct the streams state in order to clear the infinite loop. This is actually a quite common error checking procedure. Here is how it can be done.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
if (userSelection != 1 && userSelection != 2)
{
validSelection = false;
cout << "Invalid Selection. Please enter it again." << endl;
// Clears the streams error state.
cin.clear();
// Cleans up all the extra characters in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Get the user input again.
cin >> userSelection;
}
Thanks for the replies. It's not the fact of not setting the validSelection back to true (because then the infinite loop would still stop at prompting the user at cin. But this code enters an infinite loop and won't stop outputting unless you kill the program!)
So the others guys (Olysold & Zereo) must be right. The fix is a little past my understand at this point, so I'll take it not to put ASCII into an int!
And yeah I noticed the error in my if statement by not using { } but that also wouldn't affect my problem.
Thanks again
Menu operations are usually best handled with a switch IMO, include a quit case & make sure there is a default clause to handle bad input. Put the whole thing in a while loop which has bool value as an end condition, so that it loops on the bad input.
Sorry Zereo :), but I really dislike things like this:
if (userSelection != 1 && userSelection != 2)
IMO, they just look ugly & are not scalable - a switch is much easier to read & understand.
@mogglespears if you google some of my previous posts - you will see lots of examples of how this can be done.