In my program, I am trying to validate the users input an make sure that the only thing they can put in is a number between 1998-2019. The problem is, whenever I input a number first(and only a number), the program runs fine but if I put an invalid number then a character or string, the program goes into an infinite loop. The program also runs whenever I type in a character or string first then a number, but if I type in a character after I have typed in a number, it enters an infinite loop. Does anybody know why this is occurring or have a possible solution? This is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void Champs::validate()
{
while (!cin)
{
cin.sync();
cin.clear();
while (cin.get() != '\n') continue;
cout << "\nPlease enter an integer between 1998 and 2019: ";
cin >> userInputYear;
}
while (userInputYear < 1998 || userInputYear > 2019)
{
cout << "Please enter an integer between 1998 and 2019: ";
cin >> userInputYear;
cout << endl;
}
}
while (!cin)
{
cin.sync();
cin.clear();
while (cin.get() != '\n') continue;
cout << "\nPlease enter an integer between 1998 and 2019: ";
cin >> userInputYear;
}
I use it for when cin fails due to somebody inputting characters or if they try to say "two thousand". Without it, if words are entered, the program immediately enters an infinite loop.