If i want to have the user input an integer, how can i prevent them from entering a character without getting a run-time error?
Printable View
If i want to have the user input an integer, how can i prevent them from entering a character without getting a run-time error?
What I usually do (and I doubt it's the best method), is have it input to a char, and then cast it to an integer, if it's valid.
You could handle the error... I usually just put user input into a while loop and have a function check to see if an error has occured in cin. I can't explain it very well, here's some code:
This is the function I use to check cin.
I know this doesn't catch every single possible case (I'm still looking for a way to do this). For example, if you enter "3abc", it will take 3 but the rest causes an error. Apparently, it only looks at the first value.Code:short ErrChk()
{
if(cin.fail())
{
cerr << "\nInput Error! Clearing buffer... \n";
cin.clear();
cin.ignore(cin.rdbuf()->in_avail());
return 0;
}
else
{
return 1;
}
}
Casting a char as an int is probably one of the better ways to go.