Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console pause in C++?

Tags:

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?

like image 638
RCIX Avatar asked Dec 03 '10 08:12

RCIX


People also ask

Is there a pause command in C?

The pause function suspends program execution until a signal arrives whose action is either to execute a handler function, or to terminate the process. If the signal causes a handler function to be executed, then pause returns.

How do you wait in C programming?

Insert, wherever you need your program to make a delay:sleep(1000); Change the "1000" to the number of milliseconds you want to wait (for example, if you want to make a 2 second delay, replace it with "2000".

How do you pause a running code?

3 Answers. Press Control + Z . This will suspend the process and return you to a shell.

How do you stop a Vscode in C++?

Put a breakpoint at the end of main() : Then run under debugger ( F5 ). It'll stop just before program exit. That's a cool trick.


3 Answers

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.

like image 122
reko_t Avatar answered Sep 28 '22 16:09

reko_t


#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();
}
like image 22
Mephane Avatar answered Sep 25 '22 16:09

Mephane


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.

like image 3
Ignacio Vazquez-Abrams Avatar answered Sep 27 '22 16:09

Ignacio Vazquez-Abrams