208

I'm starting out in Visual C++ and I'd like to know how to keep the console window.

For instance this would be a typical "hello world" application:

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World";
    return 0;
}

What's the line I'm missing?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Raúl Roa
  • 12,061
  • 13
  • 49
  • 64
  • Amruth A. Pillai your code doesn't show "press any key to continue" thanks –  Apr 24 '13 at 00:55
  • You can print that yourself with a simple std::cout call. – Raúl Roa Jul 11 '13 at 15:34
  • 6
    The downside to all proposed solutions is that none of them work with debugging (Ctrl+F5 fails here) and when the application stops unexpectedly (all breakpoints or reads from stdin at main return fail here). What I would love to see is an in-IDE console window like Eclipse and other IDEs have. They simply keep showing the output to stdout/stderr after the program has terminated. – dr. Sybren Aug 20 '13 at 12:48
  • @sybren The accepted answer works with CTRL+F5, and why would you want a solution which works with debugging (F5)? Surely the whole point of debugging is to .. debug? What is the benefit of having a paused console after program termination, in a debugging session? – JBentley Apr 25 '14 at 08:59
  • 2
    @JBentley Eclipse and other IDEs allow you read your program's output even after the process was terminated. Surely you see the added benefit, especially when trying to find a bug? Also a breakpoint only works when you know where the program is terminating, which can be hard to tell when the output disappears from your screen. – dr. Sybren Apr 27 '14 at 13:06
  • @Sybren Could you perhaps clarify with an example of when it would be useful during a debugging session to view the final output of a terminated program? The way I see it, if you are only interested in inspecting final output, then CTRL-F5 is superior as it launches faster. And if you need more than that, then it is necessary to step through or set a breakpoint anyway, in which case the issue of not knowing the termination point is moot. By definition, if your program is running straight through to termination with no developer interaction/inspection, then you are not debugging. – JBentley Apr 28 '14 at 05:20
  • @JBentley Personally I feel there is a difference between the general "debugging" and the specific "using the VS debugger to step through the program". Also sometimes I don't know that I want to read some logged output, until after program termination. Another reason could be that the cause of termination is in the same bit of code (for example a 3rd party library) that produces the output that I want to read. That library call is either executed (prints output, then terminates) or not (prints no output). – dr. Sybren Apr 28 '14 at 14:29
  • @Sybren you never add a cout << "Test"; to check if a function gets called? – jiggunjer Jun 19 '15 at 06:37
  • @jiggunjer: sure I do, but that's beside the point. I don't see the advantage of Visual Studio actively removing the program's output after termination; I only see disadvantages. – dr. Sybren Jun 19 '15 at 12:23
  • Possible duplicate of [Preventing console window from closing on Visual Studio C/C++ Console application](http://stackoverflow.com/questions/1775865/preventing-console-window-from-closing-on-visual-studio-c-c-console-applicatio) – cxw Jul 20 '16 at 22:57

23 Answers23

408

Start the project with Ctrl+F5 instead of just F5.

The console window will now stay open with the Press any key to continue . . . message after the program exits.

Note that this requires the Console (/SUBSYSTEM:CONSOLE) linker option, which you can enable as follows:

  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.
  2. Right click on the 'hello" (or whatever your project name is.)
  3. Choose "Properties" from the context menu.
  4. Choose Configuration Properties>Linker>System.
  5. For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.
  6. Choose "Console (/SUBSYSTEM:CONSOLE)"
  7. 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.)

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

(Courtesy of DJMorreTX from http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6)

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Zoidberg
  • 4,168
  • 2
  • 18
  • 9
  • 43
    This runs the program without debugging; it's better to have a solution that works in both debug and ordinary run mode. – スーパーファミコン Mar 20 '11 at 17:17
  • 3
    For anyone who cannot get this solution to work in a makefile project, this is due to a bug in Visual Studio. I've just posted an answer with the fix. – JBentley Apr 25 '14 at 10:28
  • 1
    Can confirm! Had a console app that didn't work did this and it worked. You do not need to change your code with `cin.get(),getchar(), system("pause")` or any other garbage. Changing this works. – Callat Apr 22 '16 at 16:08
  • Ctrl+F5 means 'Start Without Debugging'. So you can't use this when debugging. Just add `system("pause");` in the end of your code. It makes sense and works fine. – Milad May 04 '18 at 07:32
42

The standard way is cin.get() before your return statement.

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World";
    cin.get();
    return 0;
}
Gordon Wilson
  • 26,244
  • 11
  • 57
  • 60
  • 4
    I know since the program is already using cout that it's already been taken care of, but I think it's worthwhile to mention that you will need to #include as well as use the std namespace: std::cin.get(). – Brian Jun 30 '09 at 11:39
  • 7
    This works but the Ctrl+F5 is much better especially when tracing global object destruction, etc. – Ternary Jun 23 '10 at 18:04
  • This is a bad solution -- what if your program exits through exit()? – Alexander Questioning Bresee Aug 03 '11 at 21:12
  • 9
    -1 for `_tmain`. I'd vote another -1 for the `cin.get()` instead of placing a breakpoint for F5 or using Ctrl F5. But I'm only allowed one downvote. – Cheers and hth. - Alf Nov 21 '11 at 17:18
  • 8
    @Cheers: What is wrong with `_tmain`? That's the standard way to write a Windows application targeting the Console subsystem. Deviating from that standard is what would be bad practice. Clearly, no one is talking about portable code here; the question says Visual C++ and `_tmain` is the signature that appears in the sample code. It's time to give up this religion. Windows is "non-standard" by default, and there are very good reasons for following *its* standards. – Cody Gray - on strike Mar 11 '12 at 06:14
  • 8
    @CodyGray: My downvote for `_tmain` is because it is totally unnecessary *non-standard* (the international C++ standard requires a plain `main`), and because it uses Microsoft's `T` macro scheme, which is needless complication and verbiage for supporting Windows 9x. If you feel deviating from the standard is bad practice, then you should absolutely not use `tmain`. There are no good reasons for using `tmain`, except for trolling or, for professionals, for displaying one's total incompetence. – Cheers and hth. - Alf Mar 11 '12 at 09:50
  • 1
    This is a hack. If you're using visual studio use the correct method, which is posed by Zoidberg. If you're not using visual studio then have the IDE, Makefile, whatever, execute a batch file which runs the result binary, then pause, so the window doesn't close. – Syndacate Jun 09 '12 at 22:05
  • 2
    "The standard way"? Surely this is just "One way"? – danio May 07 '14 at 10:24
  • This is not a hack; this is using the language to do what the language should be able to do. Relying on the IDE is the sloppy option. – Grault Aug 30 '14 at 16:32
  • @Grault It is a hack because it is using code to address a non-code related problem. The OP wants to "keep the console window open" after running his code inside the IDE. This solution will make the program pause, whether it is run in the IDE or not, and whether you already have a non-closing console window or not - a totally different outcome. Do you think the end user of the program wants an arbitrary pause every time he runs it, just because the developer needed his console window kept open while he was writing it? No - both the problem, and the solution, belong in the IDE, not the program. – JBentley Nov 25 '15 at 18:33
  • @Grault The key to understanding the issue with this solution is understanding that *keeping a console window open* (which the question wants), and *pausing the program* (which the answer solves), are **not** the same thing. Keeping the console window open happens to be a side effect of pausing the program, which is why this answer works, but is a hack. Unfortunately, in most cases, a terminating pause is not a desirable feature for a console program, which are almost invariably either run on the command line, or run in the background by some other process. – JBentley Nov 25 '15 at 18:35
  • Such wasted energy on such a quibble. "The key to understanding the issue..." Is to realize that there isn't an issue, and this is hardly worth arguing over. – Christopher Schneider Feb 08 '16 at 00:34
22

Put a breakpoint on the return line.

You are running it in the debugger, right?

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
18

Another option is to use

#include <process.h>
system("pause");

Though this is not very portable because it will only work on Windows, but it will automatically print

Press any key to continue...

Marcos Marin
  • 752
  • 1
  • 5
  • 17
8

As some have already pointed out, Zoidbergs solution does not attach the debugger, which is something you usually don't want.

The best option imo is to configure your VS accordingly (from VS 2017 onwards), by going to Tools > Options > Debugging > General. There you uncheck "Automatically close the console when debugging stops" (at the very bottom), which is probably checked in your case.

iko79
  • 1,127
  • 10
  • 23
7

For makefile projects, the accepted solution fails, due to a bug in Visual Studio (which is present at least up until version 2012 - I haven't yet tested 2013). This bug is detailed here.

In order to have the console pause after program termination on a makefile project, perform these steps (this may differ for versions other than 2010 - 2012):

1) Pass /SUBSYSTEM:CONSOLE to the linker. - EDIT: see below.

2) Open your project file (.vcxproj) in a text editor.

3) Inside the root <project> tag, insert the following:

<ItemDefinitionGroup>
  <Link>
    <SubSystem>Console</SubSystem>
  </Link>
</ItemDefinitionGroup>

4) Reload the project in your solution.

5) Run the program without debugging (CTRL + F5).

EDIT:

As per my comment below, setting the linker option /SUBSYSTEM:CONSOLE is actually irrelevant for makefile projects (and not necessarily even possible, if you are using a compiler other than MSVC). All that matters is that the setting is added to the .vcxproj file, as per step 3 above.

JBentley
  • 6,099
  • 5
  • 37
  • 72
  • I've never heard of that step 3 before. You sure that's required and works? – Mooing Duck May 28 '14 at 00:37
  • @mooingduck Yes, and after my comments on [your answer here](http://stackoverflow.com/a/23901009/1227469), I have now discovered that passing `/SUBSYSTEM:CONSOLE` to the linker is actually irrelevant - step 3 is all that matters. Bear in mind my answer relates to makefile projects - in a makefile project, the IDE has no way to know what you're passing to the linker (you might not even be using a compiler which has a `/SUBSYSTEM:CONSOLE` option), and it is the project itself which keeps track of whether or not it is meant to be a console program. I shall edit my answer accordingly. – JBentley May 28 '14 at 00:55
  • 1
    @mooingduck I can also confirm that I use this solution myself in a makefile project, with SCons as the build system, and MSVC and MinGW as compilers. There is no other way I know of to get the IDE to pause the console after termination in non-debugging mode. – JBentley May 28 '14 at 01:10
  • @JBentley, I'm trying to use Scons in the same way, thanks for your answer! Did you manage to configure Scons so that it generates projects with that tag? – Sergio Basurco Sep 18 '15 at 11:34
  • 1
    @chuckleplant I'm afraid not, my workflow was the other way around, calling SCons from VS. I initially manually created my VS makefile projects so that they passed configuration variables to my SCons script (e.g. 32/64 bit, compiler name, release/debug), which then handled the rest of the logic. In that setup there was no need for the project files to ever change, so I didn't use any auto-generating feature of SCons. I've since switched to Linux so I don't use VS anymore. Since it's a VS bug, it might be worth submitting a feature request to SCons to handle the required extra step. – JBentley Sep 18 '15 at 15:31
  • 1
    Alternatively, you could just include some Python code in your SCons script to do it yourself each time a project file is generated. I believe VS project files conform to the XML standard, so it should be fairly easy to add the missing elements, and should only require a few lines of code. I would suggest starting [here](https://docs.python.org/2/library/xml.etree.elementtree.html) (for Python 2.x) or [here](https://docs.python.org/3/library/xml.etree.elementtree.html) (3.x). [This answer](http://stackoverflow.com/q/14440375/1227469) may also be of interest. – JBentley Sep 18 '15 at 15:39
  • Awesome! This works for me on Visual Studio Community 2015 Update 1. Note that the `` tag for me looked like: ``. Cheers. – user2023370 Jan 03 '16 at 21:36
4

just put a breakpoint on the last curly bracket of main.

    int main () {
       //...your code...
       return 0;
    } //<- breakpoint here

it works for me, no need to run without debugging. It also executes destructors before hitting the breakpoint so you can check any messages print on these destructors if you have any.

Juan Castano
  • 959
  • 7
  • 10
3

Simply add a Breakpoint to the closing bracket of your _tmain method. This is the easier way plus you don't have to add code in order to debug.

Odys
  • 8,951
  • 10
  • 69
  • 111
3

You can use cin.get(); or cin.ignore(); just before your return statement to avoid the console window from closing.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
3
int main()
{
    //...
    getchar();
    return 0;
}
gonnavis
  • 336
  • 1
  • 7
  • 16
2

cin.get(), or system("PAUSE"). I haven't heard you can use return(0);

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
2

Place a breakpoint on the ending brace of main(). It will get tripped even with multiple return statements. The only downside is that a call to exit() won't be caught.

If you're not debugging, follow the advice in Zoidberg's answer and start your program with Ctrl+F5 instead of just F5.

Chad
  • 7,279
  • 2
  • 24
  • 34
2

My 2 Cents:

Choice 1: Add a breakpoint at the end of main()

Choice 2: Add this code, right before the return 0;:

std::cout << "Press ENTER to continue..."; //So the User knows what to do
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

You need to include <iomanip> for std::numeric_limits

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
2

just add system("pause") at the end of the code before return 0 like this

#include <stdlib.h>

int main()
{
    //some code goes here
    system("pause")
    return 0;
}
melpomene
  • 84,125
  • 8
  • 85
  • 148
1

I include #include <conio.h> and then, add getch(); just before the return 0; line. That's what I learnt at school anyway. The methods mentioned above here are quite different I see.

Amruth Pillai
  • 1,539
  • 2
  • 13
  • 28
  • 2
    -1: Aside from the fact that having the program itself pause is usually the wrong solution (since in most cases that is not the behaviour you want your released binary to have), conio.h is [non-standard](http://en.wikipedia.org/wiki/Conio.h), outdated, and is a C header, not C++! Unfortunately, there are a lot of bad programming practices taught in schools. – JBentley May 28 '14 at 01:31
  • One expects this to be used during testing only, it's not something you'd keep in the final version. If you're coding for Windows what's the problem with #include / _getch();? It's quicked to write than cin.get(), doesn't require to press 2 keys (at least a character+enter), and doesn't work only in debug or only in release mode. What's wrong then? – Barnack Nov 18 '18 at 17:06
1

Had the same problem. I am using _getch() just before the return statement. It works.

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Martin
  • 11
  • 1
  • You may want to add examples and explanations to your code, especially for a question asked/answered so long ago. In addition, you answer is functionally identical to several older answers, and uses the same call as another existing answer. – Clockwork-Muse Jan 11 '14 at 14:16
1

Another option:

#ifdef _WIN32
#define MAINRET system("pause");return 0
#else
#define MAINRET return 0
#endif

In main:

int main(int argc, char* argv[]) {
    MAINRET;
}
chen_767
  • 337
  • 2
  • 8
0

(Some options are may be called by different names. I do not use the english version)

I had the same problem, when I created projects with the option "empty project", Create project as "Win32-console application" instead of "empty project" . In the dialog which pops up now, you press "continue" and after that you may check the option "empty project" and press confirm. After that CTRL + F5 will open a console which does not close automatically.

Welcor
  • 2,431
  • 21
  • 32
0

I had the same problem; In my application there are multiple exit() points and there was no way to know where exactly it exits, then I found out about this:

atexit(system("pause"));

or

atexit(cin.get());

This way it'll stop no matter where we exit in the program.

0

Actually, the real solution is the selection of the project template itself. You MUST select Win32 Console Application in older VS, or fill in the project name first and then double click on Windows Desktop wizard and then select Win32 console application. Then select empty project at this point. This then allows for what the original questioner really wanted without adding extra stopping point and hold code. I went through this problem as well. The answer is also at MSDN site.

0

Here's a way to keep the command window open regardless of how execution stops without modifying any code:

In Visual Studio, open Project Property Pages -> Debugging.

For Command, enter $(ComSpec)

For Command Arguments, enter /k $(TargetPath). Append any arguments to your own application.

Now F5 or Ctrl-F5 executes Windows/System32/cmd.exe in a new window, and /k ensures that the command prompt stays open after execution completes.

The downside is that execution won't stop on breakpoints.

Jonathan Lidbeck
  • 1,555
  • 1
  • 14
  • 15
0

Just after your includes YW std::cin.clear(); // reset any error flags std::cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n'); // ignore any characters in the input buffer until we find an enter character std::cin.get(); // get one more char from the user

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 28 '22 at 21:08
-1

you can just put keep_window_open (); before the return here is one example

int main()
{
    cout<<"hello world!\n";
    keep_window_open ();
    return 0;
}
goto
  • 7,908
  • 10
  • 48
  • 58