EECS168:badInput
From ITTC
Recovering from bad user input
You can stand up to even the worst user using a combination of method in std::cin. First, we need to detected if the users input triggered the fail bit (i.e. we ask for an int and they type a char). Then we clear out the input stream because we don't know what they typed. Finally we let them try again. We can trap them in a loop until their input does not cause the failbit to trigger.
Example of getting a good int:
#include <iostream> #include <limits> int main() { int n = 0; std::cout << "Input a number: "; std::cin >> n; while ( std::cin.fail() ) { std::cin.clear(); // unset failbit // skip bad input up to the next newline std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Sorry, your input did not seem to be an int. Try again: "; std::cin >> n; } //Flush out anything left in the stream (e.g. if they type 2.5 for an int // the .5 would still be there std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "You entered: " << n; }