Why is a second cin.ignore () required?

I noticed that whenever I write a program that uses std::cin, if I want the user to press Enter to end the program, I need to write twice std::cin.ignore()to get 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 also noticed that when I do not use cinfor actual input, but rather for a call ignore()at the end, I only need one.

+5
source share
2 answers

Discl: I simplify what is actually happening.

The first serves to clear what the consuming operator (→) did not use. The second is waiting for the other \ n.

, std:: getline : std:: getline()

the_stream::ignore(std::numeric_limits<streamsize>::max(), '\n');
+8

. ? ignore n EOF, . - , 1 . Windows \r, \n - ( , ).

0

All Articles