Help > displaying error message when character is insert but declared interger

Hi,

i want to ask, how to display error message and fix the error by cin if user insert charater instead a number.

something like this;

int input;

cin >> input

-----------

but the user enter 'a' instead of a number..how to solve this? thanks!
sorry i'm really a newbie to c++
You are looking for cin.fail();
1
2
3
4
5
6
7
8
9
int input;

cin >> input;

while (cin.fail())
{
cout << "End of file or data type mismatch occured. Try again: ";
cin >> input;
}
You might want to flush the stream before grabbing anything else. You might not have to but I always do.

cin.ignore(256, '\n');

You can also just say

if (//name of stream)

to check if it's good. It will return true if the stream is still good. There are several stream flags but most of them aren't really necessary.



Last edited on
im very glad u guys would help me..
thank you very much Stewbond & IceThatJaw !
Topic archived. No new replies allowed.