Run your program from the command prompt in the first place.
Alternately, go into your executable's Advanced Preferences and find an option about "Keeping DOS Window Open" or something similar.
Alternately, you could add the line:
after the main part of your code. That way's non-portable and bad practice, though.
Just use the first method and run it from the command prompt.
As for why it happens, the system opens a window for your program, your program stops, and the system closes the window for your program since it's not running anymore.
The first method keeps the system from giving the program its own window, so it doesn't close when your program stops.
The second method keeps the system from closing the window automatically after your program ends.
The third method keeps your program running until you hit a key, and the system doesn't close the window until your program finishes.