Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ on windows closes a program immediately after launching

I installed minGW and the eclipse CDT, and the console keeps doing something weird. The code of the program is

using namespace std;
#include <iostream>

int main() {
    cout << "Hello, windows (8, c++)" << endl;
    //system("PAUSE");
    return 0;
}

You all know it, its the Hello World program. Now when I run this the Eclipse console displays some stuff about building, and then goes blank. And when I navigate to the HelloWorldProgram.exe in the explorer and run it, a windows flashes up and displays "hello world", but then immediately closes. When I do this on Mac OSX there's no problem, and the windows stays up until I decide to close it. Now I know there's a command

system("PAUSE") //I dont know what I need to import to use this. Could you tell me that too?

Which will give me more or less the same effect, but I'd like to know why Windows does it differently from OSX, and what I can do to fix it (bc this annoys the crap out of me). Looking forward to your replies!

like image 758
pipsqueaker117 Avatar asked Jan 25 '26 09:01

pipsqueaker117


2 Answers

This happens on Windows because this is just the behavior of the Windows console. You'll have to open up the console manually and then running your program through the console you've opened if you don't want the window to close automatically once the program has executed.

You may want to take a look at these:

What is the Best Practice for Combating the Console Closing Issue?

https://superuser.com/questions/186562/how-can-i-keep-the-terminal-open

like image 81
Stegrex Avatar answered Jan 28 '26 00:01

Stegrex


Don't use system("pause"), it's wrong for a multitude of reasons (read more about it here).

Put cin.get() before return and the window will stay open until you press enter.

like image 44
Gabriel Negut Avatar answered Jan 27 '26 23:01

Gabriel Negut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!