Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause Console in C++ program

Tags:

c++

Which is best way to pause the console in C++ programs?

  1. using cin.get()
  2. or using system("pause")
  3. or using C functions like getch() or getchar()?

Is it true that use of system("pause") leads to non portable code and can't work in UNIX?

Is cin.get() is better to use to pause console?

like image 388
Destructor Avatar asked Jul 16 '14 08:07

Destructor


People also ask

What is system pause in C programming?

Some common uses of system() in Windows OS are, system(“pause”) which is used to execute pause command and make the screen/terminal wait for a key press, and system(“cls”) which is used to make the screen/terminal clear.

How do I pause console in C++?

Using system(“pause”) command in C++ This is a Windows-specific command, which tells the OS to run the pause program. This program waits to be terminated, and halts the exceution of the parent C++ program. Only after the pause program is terminated, will the original program continue.

What is system pause?

The function system (“pause”) is utilized to stop the program at any time or the termination of the code and obtain the outcome of the code on the console terminal. The function system pause in C++ is typically utilized when the user desires to get the outcome in a console window.

What can I use instead of system pause?

Press CTRL+F5.


1 Answers

There might be a best way (like using the portable cin.get()), but a good way doesn't exist. A program that has done its job should quit and give its resources back to the computer.

And yes, any usage of system() leads to unportable code, as the parameter is passed to the shell that owns your process.

Having pausing-code in your source code sooner or later causes hassles:

  • someone forgets to delete the pausing code before checking in
    • now all working mates have to wonder why the app does not close anymore
    • version history is tainted
  • #define is hell
  • it's annoying to anyone who runs your code from the console
  • it's very, very, very annoying when trying to start and end your program from within a script; quadly annoying if your program is part of a pipeline in the shell, because if the program does not end, the shell script or pipeline won't, too

Instead, explore your IDE. It probably has an option not to close the console window after running. If not, it's a great justification to you as a developer worth her/his money to always have a console window open nearby.

Alternatively, you can make this a program option, but I personally have never seen a program with an option --keep-alive-when-dead.

Moral of the story: This is the user's problem, and not the program's problem. Don't taint your code.

like image 194
Sebastian Mach Avatar answered Sep 23 '22 00:09

Sebastian Mach