views:

2151

answers:

12

Hello everybody. Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there any way to stop the program from closing immediately so that I can see the fruits of my effort? Thanks in advance.

+15  A: 

Edit: As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem.

That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.


At the end of your main function, you can call:

std::getchar();

This will get a single character from stdin, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).

You need to #include <cstdio> for getchar.

James McNellis
This is probably the better of the two answers right now, but I would probably put a comment next to that to tell why you're actually doing it in real code. +1.
Billy ONeal
Another variant of this sort if to "#include <conio.h>" and use _getch().
Poni
`getchar` does not solve the problem - or only in limited circumstances, at least. It reads a char from `stdin`, but if there are already characters buffered from stdin the program will carry on without waiting regardless of whether you print a prompt or not.
Charles Bailey
@Charles: A good point. Ignoring until `\n` is a partial solution, but won't help if more than one line of input is buffered. I do not know of a standard C++ way to clear everything from an input stream. :-/
James McNellis
@James: Old, but how about `std::cin.ignore(std::cin.rdbuf()->in_avail());`? Got it from [here](http://stackoverflow.com/questions/257091/how-do-i-flush-the-cin-buffer/538629#538629).
GMan
@GMan: I don't think that actually works: the streambuf probably isn't the only buffer between the input device and `cin`; the OS is probably doing other buffering in the background and there is no standard way to inspect that buffer.r
James McNellis
@James: `while (std::cin.rdbuf()->in_avail()) std::cin.ignore(std::cin.rdbuf()->in_avail());`? :S This should really be simpler.
GMan
@GMan: It depends on how buffering is handled by the system. One case where that solution will fail: the OS has its own buffer that is used when `cin.rdbuf()` is full. You check `in_avail()`; it's full and greater than zero so you call `ignore(in_avail())` and clear the buffer; you check `in_avail()` again and it is now zero and you break out of the loop. But, meanwhile, you've typed stuff in and the OS hasn't started putting new characters into `cin.rdbuf()`. I think it's entirely dependent upon how the system buffers stdin; I'm not all that familiar with how modern systems do that.
James McNellis
[I do so little work with console input and output, I just don't know much about the details of this. And, if it were simpler, it would be C# :-P (I kid, I kid! Sort of...)]
James McNellis
+2  A: 

The solution by James works for all Platforms.

Alternatively on Windows you can also add the following just before you return from main function:

  system("pause");

This will run the pause command which waits till you press a key and also displays a nice message Press any key to continue . . .

codaddict
That sounds like a Rube Goldberg variation of a solution.
Dave Van den Eynde
@Dave Van den Eynde: It's also quite common and comes standard in the boilerplate code in DevCPP. +1
Billy ONeal
@Billy DevCPP is a piece of buggy trash that is no longer being developed. If it does it, you can almost guarantee it is wrong.
anon
@Dave on the other hand it does make it clear that this is just a bodge for an example, while std:getch could be accidentally left in real code.
Martin Beckett
+7  A: 

Why not just run the program from a console ie run the program from cmd.exe if you're using Windows. That way the window stays open after the program finishes.

[EDIT]: When I use KDevelop4 there is a fully fledged instance of Bash (a Linux CLI) running in a tab at the bottom of the IDE. Which is what I use in these sort of circumstances.

Amos
Because if you are using an IDE you don't generally use a console. You push go, the program runs, and that's it.
Billy ONeal
+1: Blindly using IDE isn't really all that helpful. Using a console to run console applications seems appropriate.
S.Lott
Any competent IDE will keep the console on screen when the app terminates - Code::Blocks for example does exactly this.
anon
@Neil Butterworth: Visual Studio does not, and I suspect that's what the OP is using. Though I agree with you that it should.
Billy ONeal
If VS can't be configured to keep the window open, then use the console itself.
S.Lott
@Billy: VS does too, press Ctrl+F5. If you use Start Debugging (F5), it assumes you actually want to debug the program.
Hans Passant
@nobugz: Unless I've screwed something up on my installation, which is quite possible, that is not the behavior in Visual Studio 2010 and I would have sworn that it's not the behavior of 2008. Is that a configurable option, do you know?
James McNellis
@James: not that I'm aware of, I've never seen or heard it not work.
Hans Passant
@nobugz: I figured it out. To get the window to stick around, you have to have /SUBSYSTEM:CONSOLE on the linker command line. The documentation says that this is the default if `main` is defined, but if I don't explicitly set it on the command line, VS kills the window when the application exits. *sigh*
James McNellis
@James: that is required to get a console window in the first place. That in turn requires main() instead of WinMain(), not the other way around. I'm a bit lost...
Hans Passant
@nobugz: If you start from an "Empty Project" instead of a "Win32 Console Application" the subsystem is not explicitly set in the project properties. If you define `main` in the project, the linker by default uses the CONSOLE subsystem. When debugging or running, you'll get a console window. However, unless you explicitly specify CONSOLE as the subsystem in the project properties, Visual Studio will not keep the console window open. I always start from an empty project and I rarely change individual project properties, so I've never seen the console window stick around. Sorry for the confusion
James McNellis
@James: If Visual Studio doesn't know you've got a console application, then Windows itself is allocating the console when the app starts, in which case it is also destroyed when the app exits.
Ben Voigt
A: 

See if your IDE has a checkbox in project setting to keep the window open after the program terminates. If not, use std::cin.get(); to read a character at the end of main function. However, be sure to use only line-based input (std::getline) or to deal with leftover unread characters otherwise (std::ignore until newline) because otherwise the .get() at the end will only read the garbage you left unread earlier.

Tronic
+2  A: 

If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.

anon
+7  A: 

If you are using Visual Studio and you are starting the console application out of the IDE:

pressing CTRL-F5 (start without debugging) will start the application and keep the console window open until you press any key.

nabulke
+2  A: 

If you are actually debugging your application in Visual C++, press F5 or the green triangle on the toolbar. If you aren't really debugging it (you have no breakpoints set), press Ctrl+F5 or choose Start Without Debugging on the menus (it's usually on the Debug menu, which I agree is confusing.) It will be a little faster, and more importantly to you, will pause at the end without you having to change your code.

Alternatively, open a command prompt, navigate to the folder where your exe is, and run it by typing its name. That way when it's finished running the command prompt doesn't close and you can see the output. I prefer both of these methods to adding code that stops the app just as its finished.

Kate Gregory
+1  A: 

Okay I'm guessing you are on Windows using Visual Studio... why? Well because if you are on some sort of Linux OS then you'd probably be running it from the console.

Anyways, you can add crap to the end of your program like others are suggesting, or you can just hit CTRL + F5 (start without debugging) and Visual Studio will leave the console up once complete.

Another option if you want to run the Debug version and not add crap to your code is to open the console window (Start -> Run -> cmd) and navigate to your Debug output directory. Then, just enter the name of your executable and it will run your debug program in the console. You can then use Visual Studio's attach to process or something if you really want to.

Polaris878
+2  A: 

I usually just put a breakpoint on main()'s closing curly brace. When the end of the program is reached by whatever means the breakpoint will hit and you can ALT-Tab to the console window to view the output.

John Dibling
A: 

Add the following lines before any exit() function or before any returns in main():

std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(1000000);
Thomas Matthews
+1  A: 

you could also stick

while(true)
    ;

or

for(;;)
    ;

at the end

Roman A. Taycher
A: 

you can even declare an integer at the beginning of your main() function (say int a;) and put std::cin >> a; just before the return value. So the program will keep running until you press a key and enter.