Reference: cin for an int inputing a char causes Loop that is supposed to check input to go wild
This is a duplicate but the canonical answer is to do:
std::cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Then do something like:
int year;
while (!(std::cin >> year)) {
std::cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "error" << std::endl;
}
// do something with year
So if your input looked like:
a
b
c
42
It will print error three times.