39

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.

Abel
  • 56,041
  • 24
  • 146
  • 247
Alex
  • 64,178
  • 48
  • 151
  • 180
  • 2
    I remember using `getch();` from `conio.h` in turbo-c while at college: but I guess I'd be down-voted to hell if I post it as an answer here :) – Amarghosh Dec 15 '09 at 16:18
  • Use `std::cin.ignore()`, look at my answer below. – Thomas Matthews Dec 15 '09 at 17:49
  • You may use system("PAUSE"); if you're not in production and for Microsoft or Borland. But I have not tried it in Borland. See the answer Wrong Way for Mike Weller below. – Douglas G. Allen May 10 '17 at 13:49

11 Answers11

71

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().

Cogwheel
  • 22,781
  • 4
  • 49
  • 67
  • 2
    is std::cin.get() only a member of namespace std? If i include , could I just go: cin.get()? – Alex Dec 15 '09 at 16:20
  • 3
    If you have `using namespace std;` in your source file, then yes. – Cogwheel Dec 15 '09 at 16:21
  • 4
    Or `using std::cin;` for that matter – Cogwheel Dec 15 '09 at 16:24
  • 1
    So, I don't even need a command like this, because the console automatically stays open if not debugging? That's nice. – Alex Dec 15 '09 at 16:36
  • Yep. Works for .Net apps too. – Cogwheel Dec 15 '09 at 17:07
  • What if in previous method I'm using `scanf`, then getch is triggered automatically. Any workaround for this? – Johnny_D Jun 29 '14 at 21:38
  • @Johnny_D: Use `cin.ignore` per other comments and answers – Cogwheel Jun 30 '14 at 18:54
  • 2
    `std::cin.get()` works for `Enter` only while `Console.ReadLine()` works for any character. – nickolay Dec 04 '17 at 20:59
  • @DaddyM sorry for the question, but just in case, have you found an analogous version to `Console.ReadLine(true)` in `C++`?. – Xam Jan 29 '18 at 21:07
  • @Xam: see Mike Weller's answer below. There isn't anything in *standard* C++ that will do what you want. You have to use compiler/OS specific stuff – Cogwheel Jan 29 '18 at 23:32
  • @Cogwheel you're right, but after some searching I found this [library](http://tapiov.net/rlutil/docs/HTML/files/rlutil-h.html) and it has a function `anykey("message")` analogous to `Console.ReadLine(true)` that works well for both Windows and Linux. – Xam Jan 29 '18 at 23:37
24

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.

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • Use system("pause") while learning only in Visual Studio or some similar IDE because it's easy to remember. But your note on this is great. I'm seeing it in these tutorials http://www.tenouk.com/ sometimes there and sometimes not but no blank inputs to hold the console open. – Douglas G. Allen May 10 '17 at 13:44
8

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.

jfseb
  • 83
  • 1
  • 3
  • this is exactly what I was looking for. In VS2008 it used to stay open but when I switched to VS2010 it started closing after running ctrl+F5. Thanks! – rem7 Feb 10 '12 at 20:20
  • Excellent answer! I was curious to find out why my console was closing even when starting without debugger. – Jaanus Varus Apr 14 '13 at 09:27
4

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;
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
2

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.

Daver
  • 483
  • 4
  • 8
1

In windows, you can use _getch() in the

<conio.h>

header.

DanDan
  • 10,462
  • 8
  • 53
  • 69
  • This will work on several windows compilers, but be warned: it isn't part of the standard, and isn't portable. – luke Dec 15 '09 at 16:52
1

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;
}
1

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;
}
S. Paris
  • 159
  • 4
  • 5
0

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.

ufukgun
  • 6,889
  • 8
  • 33
  • 55
0

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

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
-5

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

Community
  • 1
  • 1
  • 3
    On a strictly standards compliant system, this will produce several errors: It's iostream, not iostream.h, with this change there was also the introduction of the std namespace which needs to be used; conio.h is not part of the standard, thus getch() isn't either; and last but not least, this is what my compiler tells me: error: ‘::main’ must return ‘int’ – cmende Jun 11 '12 at 09:50