Daniel_V
Daniel_V

Reputation: 183

Why the output just flashes when I do not use getch()?

When I compile and run the following code in Dev C++,

#include <stdio.h>
main()
{
     printf("Hello world!");
}

The output just flashes. When I add getch, it stays.

#include <stdio.h>
main()
{
     printf("Hello world!");
     getch();
}

Why does that happen?

Upvotes: 1

Views: 2408

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158599

Your console is disappearing because it is done and the program is exiting. As you see using getch() to wait for input prevents the program from exiting but it is not portable, as an alternative you can use std::cin.get(), this is slightly different since you need to press enter though.

Upvotes: 1

Medinoc
Medinoc

Reputation: 6608

getch() causes your program to wait for user input before it terminates. An irritating thing with Win32 console applications is that the console closes as soon as the program terminates (hence why it just flashes).

This was not the case with the old DOS programs under Win9x (where the console would stay open by default, unless a checkbox was selected in the DOS shortcut properties).

If you run both versions of your program in a Command Prompt, you will see that the second one only returns to the prompt after you've pressed a key.

Upvotes: 3

Related Questions