Home c++ Pause the console in C++

Pause the console in C++

Author

Date

Category

What features in Visual Studio (besides system ("pause"); ) stop the console from closing.


Answer 1, authority 100%

If we are talking only about working in the IDE, you can use regular breakpoints and a debugger to suspend the program, no special calls in the code are needed. Moreover, using calls like system (“pause”) will make the program impossible to call normally from batch files: it will wait every time for input from the real console, even if standard input is redirected from a file and work was expected without user intervention. But, if you still really you need to pause the console whenever you start the program, there are several options:

system ("PAUSE");

Features:

  • Displays an input prompt (“Press any key”)
  • Terminates the program before pressing any key
  • Only works under Windows (other operating systems do not have PAUSE command)
  • Invokes the shell internally, so it is considered a “heavy” option (if performance matters in this case)

There is a myth that such a call is unsafe, because if you place the malicious pause.exe file in the program folder, it will be called instead of the PAUSE command. This is not the case on modern versions of Windows.

system ("PAUSE & gt; nul");

As above, but does not display the input prompt.

getchar (); //WITH
cin.get (); // C++

Features:

  • Does not display the input prompt
  • Terminates the program before pressing the Enter key
  • Standard function – works in any environment

Unlike other options, it does not break standard input redirection (just put a line of any content on the input, and the program will continue to execute).

# include & lt; conio.h & gt;
getch (); // Traditional
_getch (); // Modern version

Features:

  • Does not display the input prompt
  • Terminates the program before pressing any key
  • Non-standard function, available in DOS and Windows (other operating systems have similar analogues)

Again, there is a myth that in Windows this is some kind of DOS call and using it is a wild crime. In fact, internally it is implemented as a normal call to the WINAPI function ReadConsoleInput , with the preliminary disabling of the ENABLE_LINE_INPUT mode at the console. You can verify this by looking at the sources of the debug version of the CRT, which have been partially open for some time.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions