Arks
Arks

Reputation: 639

Cin: wait for <ENTER>. Two continues cin.ignore do not work

Here is the code:

cout << "Press <ENTER> when you are ready to procceed..." << endl;
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cin.ignore(std::numeric_limits<streamsize>::max());
cin.clear();
...
cout << "Insert " << nominal << " rubbles into money acceptor and press <ENTER>" << endl;
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cin.ignore(std::numeric_limits<streamsize>::max());
cin.clear();

The first time it waits for but the second one, it goes right throw it without any pause.

I tried to use just cin.ignore(std::numeric_limits::max(),'\n'); or cin.get() or cin.ignore() or getchar(). Nothing works.

I even tried to ask user to enter for a number:

{cout << "eof: " << cin.eof(); int num; cin >> num; cout << "eof: " << cin.eof(); }

This does not work for the second time either! It reads '32767' from cin on the second call. And outputs:

eof: 0
eof: 1

Upvotes: 1

Views: 1477

Answers (2)

Rook
Rook

Reputation: 6145

It isn't really clear to me what you are trying to do, or why. However, I wrote this simple test application, which works just fine for me:

#include <iostream>
#include <limits>

int main()
{
    std::cout << "Press enter to start\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    std::cout << "Press enter again to begin data entry\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

    int i, j;

    std::cout << "Enter a value for i\n";
    std::cin >> i;
    // skip any trailing characters after the number the user entered
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    std::cout << "Enter a value for j\n";
    std::cin >> j;
    // skip any trailing characters after the number the user entered
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

    std::cout << "i was " << i << ", j was " << j << "\n";

    std::cout << "Press enter to continue\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    std::cout << "Press enter again to exit\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

    return 0;
}

Leaving in the cin.ignore(std::numeric_limits<streamsize>::max()); lines that you had in your code forces me to hit enter (to trigger the "ignore until \n code) and then hit control-D to send an EOF to trigger the second ignore call. I could not replicate your "it goes right throughit without any pause" condition.

This code built and ran correctly under GCC 4.7.2 and VS2013 Express.

Upvotes: 2

Martin Pfeffer
Martin Pfeffer

Reputation: 12627

try:

cin.sync()

maybe it will work...

Upvotes: 0

Related Questions