...

View Full Version : How to FLUSH the user input CIN stream? [C++]



Shaitan00
06-01-2009, 03:52 AM
How can I flush out the rest of the users input (cin)?
For example I have the following code:



char cCommand;
cout << "Enter: ";
cin >> cCommand;
if (cCommand == 'c')
{
... do something ...
cout << "Valid Input";
}
else
{
cout << "Invalid Input";
}


Now this works perfectly fine when the user enters a single character, but what if the user enters something like this:
Enter: abc
In this case the user enters "abc" my code will out the following:
Invalid Input
Invalid Input
('a' & 'b' are invalid but 'c' is valid)

This is not the behavior I want... Seeing as 'abc' is not 'c' I want to output "Invalid Input" and then FLUSH the rest and force him to retry, I do not want to continue and process the "bc" parts of the input ...

Is there a way, after cout << "Invalid Input" to somehow FLUSH the rest of what the user entered so that he is forced to start over, and it does not process the rest of his input?
Thanks,

oracleguy
06-01-2009, 09:23 AM
Yes you can flush the user input.



cin.clear();
cin.ignore(cin.rdbuf()->in_avail());



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum