Antonio Garosi
Antonio Garosi

Reputation: 51

A good, simple, portable solution for waiting until enter is pressed in C++

Why not this?

cin.ignore (getchar(),'\n');

I'm not a professional programmer, and barely I can consider myself an amateur, but this is my little effort.
After looking thoroughly between all the solutions on the web that could be simple, portable and easy to understand (especially for a newbie like me), I haven't seen nothing really acceptable (especially for a newbie like me).
After many, many unsuccessful tries I wrote this line. And it worked!
And to me it sounds like a pretty elegant solution.
I mean: it's just one line of code, it's easy to remember, it doesn't need any further declared variable, you don't have to get in too much abstraction to understand it.
And it works, in every scenario I tried it.
If it's not a good solution, is there anybody good-willing enough to explain it?

[EDIT]

Thanks you all for all the proprer answers. But either me or you are missing the point. What I'm questioning about is not if the solution I posted was working or not, because it works! At least on my computer, and in all the executables I'm working on (I don't want to seem stubborn, try for yourselves for taking away credit from me. An example as I use it is at the end). And none of the side effects you are talking about are showing up. The line answers to my first enter, and it answers only to an enter - not "any" char. My concerns are about the fact that I haven't seen it wrote anywhere, and considering myself the poorest of the programmer that surprised me to have found a solution from scratch.

short WaitForEnter ()
{
    cout << "Press ENTER to continue\n";
    cin.ignore (getchar(),'\n');
    return 0;
}

Upvotes: 1

Views: 147

Answers (1)

Pandrei
Pandrei

Reputation: 4951

Let's look at definition of ignore:

istream& ignore (streamsize n = 1, int delim = EOF);

Extract and discard characters Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.

The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.

So your line of code will wait for you to enter one character in to console (any character) not enter (\n);

Upvotes: 1

Related Questions