I'm trying to filter out invalid user inputs in a small C++ program using the following chunk of code:
int selection = -1;
while (!(selection >= 1 && selection <=4))
{
cin >> selection;
if (!(selection >= 1 && selection <=4))
{
cout << "invalid selection!" << endl;
cout << "selection: ";
}
}
It seems to work fine when I enter any numerical value that is either inside or outside the range i want to filter. However strange things happen when I enter invalid values such as values larger than the maximum storable int or characters. The code loops through and skipping the "cin" command.
How do I fix this?
Thanks