views:

6288

answers:

10

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?

+1  A: 

A simple approach is to wait for an input character before exiting:

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

    char c;
    cin >> c; // wait for a character + enter key
    return 0;
}
Dave Ray
+3  A: 

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
Much more elegant.
Dave Ray
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 <iostream> as well as use the std namespace: std::cin.get().
Brian
This works but the Ctrl+F5 is much better especially when tracing global object destruction, etc.
Travis
A: 

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

CMS
+3  A: 

Another option is to use

system("pause");

Though this is not very portable so it will only work on Windows, but it will automatically print "Press any key to continue . . ." for you.

Marcos Marin
A: 

It's a lot easier just to use:

return(0);

This will automatically add the "Press any key to continue" prompt.

A: 

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

+12  A: 

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.

Zoidberg
Much better solution especially when tracing destruction of global objects.
Travis
Agreed. This is a better way.
Gordon Wilson
A: 

Put a breakpoint on the return line.

You are running it in the debugger, right?

280Z28
A: 

I have this problem but unfortunately I have tried the Ctrl+F5 to run it, even tried system("pause") and cin.get() but nothing worked. Anything else I could try?

Ninjaboi
A: 

Not sure how to know if I am in the debugger, if by that you mean I click 'Start Debugging' then yes.

Ninjaboi