I\'m having a problem with what should be incredibly simple code. I want to take in an integer between 1 and 3 with error checking. It works fine for checking for numbers
Most of these answers include unnecessary complexity.
do{
cout << "\nPlease enter a number from 1 to 3:" << endl;
cout << "-> ";
if(!cin){
cout << "Invalid input"
cin.clear()
cin.ignore(numeric_limits::max(), '\n');
}
}while(!(cin >> input))
Use numeric_limits
to completely clear the
buffer after a failed cin
.
Use cin.clear()
to reset the fail flag on cin
so !cin
wont
always evaluate false.
cin.fail()
is fine. However some would consider !cin
more natural.
from my previous post https://stackoverflow.com/a/43421325/5890809