In this part of the program, I am asking the user to select an option from the menu. The only acceptable input should be 1, 2, or 3. The validation is working fine... except when the user enters a character that is not a number. For example, if you enter "f", the program spams the validation statement infinitely. How can I make my program handle unexpected input in this way?
int myInt;
std::cin >> myInt;
if(std::cin.fail()) // In abstract, this is basically checking if the previous input matches
{ // what was suppose to be inputted (i.e. a character input for an int data type)
// If it DOES NOT, then perform the following actions...
std::cin.clear(); // Clear the input stream
std::cin.ignore(99999, '\n'); // Ignore the rest of the input.
}
Now you need to figure out how to incorporate this into your program.
Have you tried the perfectly good solution that @fiji885 demonstrated for you?
- change your input variable expecting 1, 2 or 3 to an int?
- check the state of the stream for invalid input;
- clear any failed state and remove anything left in the input buffer.
Seems a good solution to me.