How do I keep the console open?

The 'Hello World' program below executes and immediately closes the console window. I'm using Microsoft Visual Studio as my IDE.

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

int main()
{
  cout << "Hello World" << endl;
  return 0;
}


Is there are better substitute to keep the console window open besides the code below (entering system("pause");that as I understand it, doesn't always work on every system?

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
  cout << "Hello World" << endl;
  system("pause");
  return 0;
}
system("pause"); is maybe the only way to keep the console window open and its only working on windows
I think this is mostly a problem on Windows. Console programs are meant to run from the console, and if you do that it will not be a problem because the console window will stay open. On Linux when you double click on a executable file it runs the program but it doesn't normally automatically open a console window where you can read/write the input/output.

If you write a program just for yourself, for learning purposes, I don't think you should worry about using system("pause"). Using standard stream functions like cin.get() and similar is much more problematic because it doesn't work if cin is in an error state, or contains the wrong input etc. If you really want the console program to be kept open in a real program I think the proper way is to use a library like PDCurses or some functionality in the WinAPI.

Sometimes it makes sense to ask the user when he want the program to end. If you are doing a game you could always ask the user if he wants to play again, that way you avoid having to keep the window open after the program has ended.

loop:
	run game
	ask user "Do you want to play again?"
	if user don't want to play again:
		stop looping
Last edited on
u can use cin.get(); instead of system("pause");
The top post on this forum is about that topic.
http://www.cplusplus.com/forum/beginner/1988/
Topic archived. No new replies allowed.