How to FLUSH the user input CIN stream? [C++]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
How can I flush out the rest of the users input (cin)?
For example I have the following code:

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,
 
Have you tried reading a string from the stream? This should read an entire line. Then you could process the string char by char, or validate it as a whole.
 
Back
Top