Window closes instantly

From Compsci.ca Wiki

Revision as of 00:28, 18 October 2008 by Wtd (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

It's quite common for new programmers to run into the confusing situation where their program compiles, but then when run, the console window in which the output appears closes instantly.

Let's look at an example of a program where this might be seen.

#include <iostream>

int main()
{
    std::cout << "Hello, world!" << std::endl;
}

When the program is run, a console window very very briefly appears with the output, but then closes. On modern PCs with very fast processors, this may appear to happen instantly.

The problem is that the console window only exists for the sake of the program. As soon as the program has completed, it is closed. For very short, simple programs, this happens very quickly.

There are two solutions:

  • Open a command prompt window and execute the program from there. The window now has another reason to exist, and when the program finishes, it remains open, awaiting your next command.
  • This is the poorer choice, and only masks the problem. Add code to your program that prompts the user for input. The program will not complete until the user actually does input something, meaning that in the meantime the console window remains open.
Personal tools