C++ - Hold the console window open?


My question is super simple, but I'm transitioning from C# to C++, and I was wondering what command holds the console window open in C++?

I know in C#, the most basic way is:


Or if you want to let the user press any key, its:


How do you do this in C++? The only reason I ask this simple of a question here, is that I haven't been able to find a good and clear answer out there on the internet.

4/8/2012 3:29:54 PM

Accepted Answer

How about std::cin.get(); ?

Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main().

12/15/2009 4:22:41 PM

The right way


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>

HANDLE hStdOutput;
BOOL bUsePause;

void main(void)
        hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
        if (!GetConsoleScreenBufferInfo(hStdOutput, &csbi))
                printf("GetConsoleScreenBufferInfo failed: %d\n", GetLastError());

        // if cursor position is (0,0) then use pause
        bUsePause = ((!csbi.dwCursorPosition.X) &&

        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:


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.


This is not a part of the C/C++ standard library. It is just a compiler extension and some compilers won't support it.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow