I’m trying to take an integer from the user. I’m using cin.ignore to make sure that the input is an int. However, when it is not an int, it causes the program to enter an infinite loop.
int steps = 0;
while (steps<2 || steps>100)
{
char tmp[1000];
cout << "Zadejte pocet cyklu: ";
cin >> steps;
cin.ignore(numeric_limits<int>::max(), '\n');
if (!cin || cin.gcount() != 1)
{
cin.getline(tmp,1000);
steps = 0;
}
}
If the input stream doesn’t contain an integer when you do
cin >>, the stream enters an error state, which must be explicitlysteps
cleared (
cin.clear()). Until then, the error state remains, and allfurther attempts to input will be treated as no-ops.