23

In C# you can cause the console to wait for a character to be input (which is useful for being able to see the last outputs of a console before the program exits). As a beginner in C++, i'm not sure what the equivalent is. Is there one?

sbi
  • 219,715
  • 46
  • 258
  • 445
RCIX
  • 38,647
  • 50
  • 150
  • 207

4 Answers4

35

The simplest way is simply:

std::cin.get();

You can print something like "Press any key to continue..." before that. Some people will tell you about

system("pause");

But don't use it. It's not portable.

reko_t
  • 55,302
  • 10
  • 87
  • 77
  • 8
    Note that while `cin.get()` is supposed to read a single character it's probable that your terminal does line buffering so that you will have to press enter before the call to `get()` returns. – Alex Jasmin Dec 03 '10 at 08:54
  • Behavior of those two samples doesn't behave the same, cin.get() waits for ENTER, and system("pause") returns immediately once user presses ANY key. – SoLaR Jun 06 '21 at 14:30
5
#include <stdio.h>
// ...
getchar();

The function waits for a single keypress and returns its (integer) value.

For example, I have a function that does the same as System("pause"), but without requiring that "pause.exe" (which is a potential security whole, btw):

void pause()
{
  std::cout << std::endl << "Press any key to continue...";
  getchar();
}
Mephane
  • 1,984
  • 11
  • 18
  • 5
    There is no `pause.exe`; `pause` itself is a built-in command in the Windows shell. – Greg Hewgill Dec 03 '10 at 11:28
  • 2
    Well, I was under the impression that the command pause resulted in running a whole process which is basically the program "pause". For example, `system("notepad")` (on windows) starts notepad, so this command definitely *can* launch other executables. – Mephane Dec 08 '10 at 11:52
  • Not the same: getchar(); waits for ENTER key to be pressed before returning – SoLaR Jun 06 '21 at 14:32
3

There is nothing in the standard, and nothing cross-platform. The usual method is to wait for <Enter> to be pressed, then discard the result.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • The C++ standard library is incorporated in the ANSI/C++ ISO Language standard and contains `std::cin` of class `istream`. This is cross-platform and not "nothing". – Abel Apr 08 '12 at 15:27
1

The incorrect solution would be to use system("pause") as this creates security holes (malicious pause.exe in directory!) and is not cross-platform (pause only exists on Windows/DOS).

There is a simpler solution:

void myPause() {
    printf("Press any key to continue . . .");
    getchar();
}

This uses getchar(), which is POSIX compliant (see this). You can use this function like this:

int main() {
    ...
    myPause();
}

This effectively prevents the console from flashing and then exiting.

adrian
  • 1,439
  • 1
  • 15
  • 23