tags:

views:

670

answers:

2

I've noticed that whenever I write a program that uses std::cin that if I want the user to press Enter to end the program, I have to write std::cin.ignore() twice to obtain the desired behavior. For example:

#include <iostream>

int main(void)
{
    int val = 0;
    std::cout << "Enter an integer: ";
    std::cin >> val;

    std::cout << "Please press Enter to continue..." << std::endl;

    std::cin.ignore();
    std::cin.ignore();  // Why is this one needed?
}

I've also noticed that when I'm not using cin for actual input but rather just for the ignore() call at the end, I only need one.

A: 

That's strange. What platform are you running on? By definition, ignore extracts and discards n characters from the input stream or if it hits EOF it stops. If you do not specify any parameters it extracts 1 character. On Windows, line ending involves both a \r and a \n -- a total of two characters (a carriage return followed by a newline).

dirkgently
I thought that at first also, but the library is supposed to abstract whatever line ending scheme the platform uses, and your application code should only see "\n".
Brian Neal
+6  A: 

Discl: I'm simplifying what really happens.

The first serves to purge what the extraction operator (>>) hasn't consumed. The second waits for another \n.

It is exactly the same when we do a std::getline after an extraction: a the_stream::ignore(std::numeric_limits<streamsize>::max(), '\n'); is required before the call to std::getline()

Luc Hermitte
Ah I see. So if the characters you enter at the first prompt are "123\n", you're saying that operator>>() leaves that "\n" alone, and the 1st ignore() reads it; then the 2nd ignore() waits for you to press a key and reads that (the 2nd "\n"). +1.
j_random_hacker
That's the idea.
Luc Hermitte