Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a second cin.ignore() necessary?

Tags:

c++

input

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.

like image 804
Cristián Romo Avatar asked Mar 10 '09 16:03

Cristián Romo


1 Answers

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()

like image 125
Luc Hermitte Avatar answered Sep 28 '22 01:09

Luc Hermitte