Window closes instantly

From Wiki

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