Here i get input for accNum and gives out error message when the input is not an integer. However, whenever an alphanumeric input is entered (integer followed by alpha), the program skips the error message and continues next lines of codes.
So what's wrong with my code here?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int accNum;
cout << "\nPlease enter Account Number." << endl;
while (true) // loops until valid account number is entered
{
cin >> accNum;
if (!cin)
{
cout << "\nERROR! \nPlease enter a valid Account Number. (Numbers only)" << endl;
cin.clear();
cin.ignore(100, '\n');
}
else
{
break;
}
The cin >> operator stops when it encounters a non-numeric. That is not a fail condition, therefore you take the else clause. Because it encountered leading numerics, those were converted and the >> operator is satisfied.
Thanks.
But I've got another problem.
I have a switch statement which takes char input to be evaluated.
It has the same problem as the one above, but how can I do it at the default case? (or is it no way for switch statement?)
skips the default when input is (r2, re, rr, etc.):