Assuming that you are indeed working on Windows, the worst thing about system("PAUSE")
is that it betrays a fundamental misunderstanding of your operating system's architecture. You do not need a code replacement for system("PAUSE")
, because the code is the wrong place to solve the perceived problem.
Beginners like to put system("PAUSE")
or even a portable alternative like std::cin.get()
at the end of a program because otherwise "the window disappears" as soon as the program ends. Such logic, however, is deeply flawed. The window which you probably see while the program runs and which has made you ask this question is not part of the program itself but part of the environment in which the program runs.
A typical console program, however, must not assume details about the environment in which it is executed. You must instead learn to think in more abstract terms when it comes to input and output via std::cout
and std::cin
. Who says that your program is even visible for a human user? You may read from or write into a file; you may use pipes; you may send text to a network socket. You don't know.
#include <iostream>
int main()
{
std::cout << "Hello world\n"; // writes to screen, file, network socket...
}
Opening a graphical window and displaying text output on the screen is not in the scope of your program, yet using system("PAUSE")
assumes exactly that one single use case and breaks all others.
If you use an IDE like Visual Studio and are annoyed by the fact that pressing F5 eventually results in the window disappearing before you have had the chance to see all output, here are three more sensible alternatives than manipulating the program itself:
- Demystification. Observe that what Visual Studio really does is invoking the Visual C++ compiler behind the scenes in order to create an *.exe file. Open your own console window with
cmd
or with Tools > Visual Studio Command Prompt, locate the directory of that *.exe file and run it there (you should eventually also learn to start the compiler without Visual Studio's help, because that will give you a deeper understanding of the C++ build process).
- Press CTRL+F5.
- Place a breakpoint at the end of your code. Read the documentation if you don't know how.