質問

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?

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top