[c++] 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:

Console.ReadLine();

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

Console.ReadKey(true);

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.

This question is related to c++ windows console

The answer is


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.


As Thomas says, the cin ignore is a good way. To always wait for user to press enter (even if exit is used), register a function atexit:

#include <iostream>

void pause()
{   ::std::cout<<"\nPress ENTER to exit.";
    ::std::cin.sync();
    if(::std::cin.get()!='\n')
        ::std::cin.ignore(0xFFFFFFFF,'\n');
}

int main()
{
    atexit(pause);

    // whatever

    return 0;
}

hey first of all to include c++ functions you should use

include<iostream.h> instead of stdio .h

and to hold the output screen there is a simple command getch();
here, is an example:
   #include<iostream.h>
   #include<conio.h>
   void main()  \\or int main(); if you want
  {
    cout<<"c# is more advanced than c++";
    getch();
  }

thank you


I use std::getwchar() in my environment which is with mingw32 - gcc-4.6.2 compiler, Here is a sample code.

#include <iostream>
#include "Arithmetics.h"

using namespace std;

int main() {
    ARITHMETICS_H::testPriorities();

    cout << "Press any key to exit." << endl;
    getwchar();
    return 0;
}

In windows, you can use _getch() in the

<conio.h>

header.


A more appropriate method is to use std::cin.ignore:

#include <iostream>

void Pause()
{
   std::cout << "Press Enter to continue...";
   std::cout.flush();
   std::cin.ignore(10000, '\n');
   return;
}

If your problem is retaining the Console Window within Visual Studio without modifying your application (c-code) and are running it with Ctrl+F5 (when running Ctrl+F5) but the window is still closing the principal hint is to set the /SUBSYSTEM:CONSOLE linker option in your Visual Studio project.

as explained by DJMooreTX in http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6

1) Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.

  1. Right click on the 'hello" (or whatever your project name is.)

  2. Choose "Properties" from the context menu.

  3. Choose Configuration Properties>Linker>System.

  4. For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.

  5. Choose "Console (/SUBSYSTEM:CONSOLE)"

  6. Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)

Now do Boris' CTRL-F5, wait for your program to compile and link, find the console window under all the other junk on your desktop, and read your program's output, followed by the beloved "Press any key to continue...." prompt.

Again, CTRL-F5 and the subsystem hints work together; they are not separate options.


Roughly the same kinds of things you've done in C#. Calling getch() is probably the simplest.


if you create a console application, console will stay opened until you close the application.

if you already creat an application and you dont know how to open a console, you can change the subsystem as Console(/Subsystem:Console) in project configurations -> linker -> system.


You can also lean on the IDE a little. If you run the program using the "Start without debugging" command (Ctrl+F5 for me), the console window will stay open even after the program ends with a "Press any key to continue . . ." message.

Of course, if want to use the "Hit any key" to keep your program running (i.e. keep a thread alive), this won't work. And it does not work when you run "with debugging". But then you can use break points to hold the window open.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working