cin question with integers

I've noticed that if I want to take something off the command line (UNIX/Linux) with cin and put it in an int variable, things like "4four" would work.

For example:

Enter a number: 4b

This would put 4 into the variable. cin.good() says it's good. Does it disregard the b? Does the b do anything? Is it potentially bad?

And more importantly, how would I catch that error?

Thanks.
The "b" remains in the buffer for when you next call cin>>. And you can't really catch it, as there is no error there. It's the expected behavior. You could try using a stringstream to read the data and check if there is anything left over if you want to be sure there is no extraneous data.

It's a bit sloppy but here is an example of what I was thinking:
1
2
3
4
5
6
7
string temp;
int myint = 0;
cin.getline(temp);
stringstream ss(temp) >> myint;
if(!ss.str().empty() || !ss.good()) {
    // extraneous data
}
Thank you. ^_^
Topic archived. No new replies allowed.