Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jan 2005
    Posts
    74
    Thanks
    0
    Thanked 1 Time in 1 Post

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

    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,

  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    Yes you can flush the user input.

    Code:
    cin.clear();
    cin.ignore(cin.rdbuf()->in_avail());
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •