|
Zolaboony (1) |
May 19, 2008 at 5:30am |
Hi, i am new to C++ and have just written my "Hello World" program. It worked all right but the console/cmd closes down instantly. If you tell me why it is closing down it would be very helpful. |
Duoas (1617) |
May 19, 2008 at 5:40am |
It is because your IDE is too stupid to know that a console application run from the IDE should have an automatic pause at the end.
Add the following to the end of your main() function to fix it:
1 2 3 4 5 6 7
|
...
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
|
You'll need to #include <limits>
Enjoy. |
ropez (312) |
May 25, 2008 at 1:44pm |
First I would search for the setting in my IDE that says "Keep console window open after program terminates".
If I didn't find it, I'd send a request for it to be included in the next version.
In the meantime: All the suggestions so far assumes that the program reach the end of main. Neither of you considered exceptions, or something like this in main:
1 2
|
if (somethingFailed())
return SOME_ERROR_CODE;
|
I suggest creating this small tool:
1 2 3 4 5 6 7 8
|
class KeepRunning {
public:
~KeepRunning() {
// Whatever code you prefer to keep the program running, e.g.
system("pause"); // "Press enter"
sleep(5); // Wait 5 seconds
}
};
|
In your main function:
1 2 3 4 5 6
|
int main() {
KeepRunning kr;
// code
} // Program stops here
|
This way the program must keep the console open, even if it doesn't reach the end of main.
BTW: Of course, remember to remove this code before the program is "released". |
|