The right way
cin.get();
cin.get()
is C++ compliant, and portable. It will retrieve the next character from the standard input (stdin). The user can press enter and your program will then continue to execute, or terminate in our case.
Microsoft's take
Microsoft has a Knowledge Base Article titled Preventing the Console Window from Disappearing. It describes how to pause execution only when necessary, i.e. only when the user has spawned a new console window by executing the program from explorer. The code is in C which I've reproduced here:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
CONSOLE_SCREEN_BUFFER_INFO csbi;
HANDLE hStdOutput;
BOOL bUsePause;
void main(void)
{
hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleScreenBufferInfo(hStdOutput, &csbi))
{
printf("GetConsoleScreenBufferInfo failed: %d\n", GetLastError());
return;
}
// if cursor position is (0,0) then use pause
bUsePause = ((!csbi.dwCursorPosition.X) &&
(!csbi.dwCursorPosition.Y));
printf("Interesting information to read.\n");
printf("More interesting information to read.\n");
// only pause if running in separate console window.
if (bUsePause)
{
int ch;
printf("\n\tPress any key to exit...\n");
ch = getch();
}
}
I've used this myself and it's a nice way to do it, under windows only of course. Note also you can achieve this non-programatically under windows by launching your program with this command:
cmd /K consoleapp.exe
The wrong way
Do not use any of the following to achieve this:
system("PAUSE");
This will execute the windows command 'pause' by spawning a new cmd.exe/command.com process within your program. This is both completely unnecessary and also non-portable since the pause command is windows-specific. Unfortunately I've seen this a lot.
getch();
This is not a part of the C/C++ standard library. It is just a compiler extension and some compilers won't support it.