ignore causes empty string

Oct 16, 2015 at 3:20am
I'm trying to understand why exactly cin.ignore causes my string to be empty in this code:

1
2
3
4
5
6
7
    string text;
    do
    {
        cout<<"Enter a string"<<endl;
        cin.ignore(INT_MAX,'\n');
        getline(cin,text);
    }while(text.length()<1);

If I remove the cin.ignore line it will read properly. If I leave it there, I get an endless loop.

As far as I understand, ignore flushes the buffer, so in case there was anything stored, it leaves it "clean" and ready to get the next keyboard input.

I usually use cin.ignore right after a "cin >> somevariable" to empty the buffer in case I need to use getline afterwards (read it here: http://stackoverflow.com/a/25476169/2011041). Is that correct?

And what exactly is going on with this code that causes the endless loop?
Thanks
Last edited on Oct 16, 2015 at 3:24am
Oct 16, 2015 at 3:31am
As far as I understand, ignore flushes the buffer, so in case there was anything stored, it leaves it "clean" and ready to get the next keyboard input.


ignore does not "flush" the buffer. It ignores things, thus the name. If there isn't anything to be ignored already in the stream it waits for you to enter something to ignore.
Last edited on Oct 16, 2015 at 3:32am
Oct 16, 2015 at 3:32am
Ahh, I see! I didn't know it would "wait" for me to enter something to ignore, hehe. Thanks for the clarification!!
Topic archived. No new replies allowed.