clearing the buffer with cin

I have a function the gets user input with cin, and i need the input to be an integer between 1 and 12, the program works fine unless the user enters more than i want them to. For example if the user enters 5.5 instead of 5, my program goes into an endless loop. I used floor() to get the input down to 5, but the rest i guess is still in the buffer the next time cin runs.
the problem is the dot.
If you are reading integers, >> will stop reading at the first non-digit character ( eg: the '.' ) the next input operation will try to read from that character.
If the non-digit character was a space, it won't cause any problem ( spaces are ignored by >> ) but if it's something else ( as in the case with 5.5 ) cin state will be set to fail and any other input operation will fail as well.

When you are in that situation, you need to discard the characters that you don't want and clear the error state.
Another solution would be to read input from cin as a string ( with getline ) and then try to convert the string into an integer.
The latter solution is described here: http://www.cplusplus.com/forum/articles/6046/
I think the best option is reading it as a string, as Bazzy said, because the "proper" behavior, IMO, wouldn't be to ignore the fractional part, but to signal an error indicating that the input is unacceptable.

EDIT: I guess that could also be done by trying to read an int directly and checking the stream's state, though.
Last edited on
thanx guys, i'm actually sick as hell at the moment, but im going to dive into ya'lls (yes i'm from the south) advice in the mornig when i'm hopefully feeling better. In the mean time, i'm a little confused about a line of code from the above link:
1
2
3
4
 stringstream myStream(input);
   if (myStream >> myNumber)
     break;
   cout << "Invalid number, please try again" << endl;


on the 2nd line, what does it mean to use >> as a comparison?

g'nite guys. like i said, i'll dive into it tomorrow, right now i'm spending more time in the BR than at my computer. :(
>> is not used as a comparison, it's like the usual stream operation myStream >> myNumber ( reads from myStream to myNumber )
Which returns a stream, that returned stream can be used to test whether the last input operation failed or succeeded.
Equivalent alternatives to that comparison are:
1
2
3
   myStream >> myNumber;
   if (myStream)
     break;
and
1
2
3
   myStream >> myNumber;
   if (myStream.good())
     break;
right on, gothca. Feeling better, gonna dive into it tonight. Thanks again guys.
it's been a few days since i posted, but i'm jumping back into the problem. I think filipe is right, the best thing is to signal an error, because i instruct the user to enter a single int, and if they don't i should kick out their intput and tell them to re enter it.
Topic archived. No new replies allowed.