Clear Input Stream

Aug 12, 2011 at 3:06am
I know that this question has been asked and answered a million times, but I'm just not handling it correctly. I need to solicit a user response, execute a bunch of code, then return to the start of the loop and solicit another response. Before reiterating, I need to clear the cin stream so that the next response is captured correctly. This is my code. I thought that I was handling this, but I'm not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
    string response;
    bool run_again = true;

    while (run_again)
    {
        cout << "Enter something" << endl;
        cin.get();
        getline(cin, response);
        
        //switch statement using response

        cin.clear();
        cin.ignore();
    }
}


Anybody see what I am doing wrong? How do I simply reset cin, so that it has no value when the loop reiterates?

Thanks.
Aug 12, 2011 at 3:16am
Put
 
cin.ignore(numeric_limits<streamsize>::max(),'\n');

in place of cin.ignore();
No need of clear();
Aug 12, 2011 at 3:31am
Thanks. This seems to work, but it has one problem. It seems to make the program pause until the enter key is pressed. It looks to the user like the program has crashed. I don't want the program to pause, I just want the cin stream to be reset, so that it is free to accept user input like it did on the very first iteration. What else should I do? Thanks.
Aug 12, 2011 at 3:40am
closed account (DSLq5Di1)
http://www.cplusplus.com/reference/iostream/istream/sync/

1
2
3
4
5
6
7
8
9
10
11
12
13
    while (run_again)
    {
        cout << "Enter something" << endl;
        cin.get();

        cin.sync(); // clear the input buffer
        getline(cin, response);
        
        //switch statement using response

        cin.clear();
        cin.ignore();
    }
Aug 12, 2011 at 4:42am
That seems to work Thanks as always!
Topic archived. No new replies allowed.