After compiling console programs the console window closes immediately after running. What is the best practice for keeping it open? I\'ve searched google loads, I\'m used t
I use:
cin.get()
I heard it was less costly than system("PAUSE") and it works on POSIX systems too. There's a great link that goes into detail about this.
Resist the temptation to do anything. Well behaved command line programs exit when they've finished running reporting a status via their exit code. This enables them to be scriptable and 'good citizens' in automated environments. Even in an interactive environment, why force the user to make an extra key press just because of your debugging environment?
If you run, rather than debug then Visual Studio will open a console windows that pauses after your application exits so that you can still view the output. I don't know why the behaviour is different when you debug, perhaps because you have breakpoints available so if you want to see the output at various stages you can place breakpoints after the relevant output statements, or at the end of main
or enable various 'stop on exception throw' options.
Whatever the reason, I've never felt compelled to compromise the behaviour of my application just to enhance my debugging experience.
cin
is grossly inelegant but easy for the forgetful to derive:
{
char c;
std::cin >> c;
}
That holds the window open until you type a character /* edit */ and hit enter.
std::cin.get()
will close the window the moment you type a character, which, depending on how easily you become habituated, runs a marginally greater risk of "whoops, I wish I hadn't closed that!" than the two-keystroke operator>>(istream &)
.
Both differ from a system("pause")
in that they return in a program-accessible way the value of the character you typed, so, if as not infrequently happens, one kludge leads to another, you can write a switch statement based on what you typed to (for example) exit immediately, write some values to a log, run it again, etc.
I tend to use system("PAUSE");
which gives you a
Press any key to continue . . .
message.
When I'm using Visual Studio and I don't need debugging I just run it using Ctrl+F5 keystroke – and it prevents console from closing.
Run your program in a console, which would be the expected way of running a console program ...
Alternatively, you can make a little batch file to execute your program that would have:
REM batch file to launch program
yourprogram.exe
PAUSE
and the PAUSE
cmd.exe command will ask to user to press any key.