When working with console applications, you may encounter the problem that the console window (sometimes referred to as a "DOS" window or terminal) in which your program displays output closes before the output can be viewed. There are several ways around this problem. Options include:
- Run the program from the command prompt. Since you open the console window yourself it will not close when your application finishes.
- Use an Integrated Development Environment which keeps the console open for you. Known IDEs that has this functionality are:
- Microsoft Visual Studio (when using Execute to run the program)
- Using a debugger and setting a breakpoint at the closing } for the main function. Microsoft Visual Studio incorporates a very easy-to-use debugger that can do this.
- Use getchar() or other input functions to keep the console open until the user presses enter. To eat up any characters along with the newline, a favourite is the following (for C):
int c; while((c = getchar()) != '\n' && c != EOF);
If there is any input in the input stream, for example a newline from scanf(), you will need to put that code twice, e.g.:
int c; while((c = getchar()) != '\n' && c != EOF); while((c = getchar()) != '\n' && c != EOF);
- And for C++, one possibility is:
#include <iostream> #include <ios> #include <limits> // ... std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin.get();
- Use a non-standard call to getch() or system("PAUSE") or similar -- this has the advantage that you can press any key, not just enter, to close the window, but is inherently unportable (thus we do not recommend this approach).