Pause Console in C++ program

C++

C++ Problem Overview


Which is best way to pause the console in C++ programs?

  1. using cin.get()
  2. or using system("pause")
  3. or using C functions like getch() or getchar()?

Is it true that use of system("pause") leads to non portable code and can't work in UNIX?

Is cin.get() is better to use to pause console?

C++ Solutions


Solution 1 - C++

There might be a best way (like using the portable cin.get()), but a good way doesn't exist. A program that has done its job should quit and give its resources back to the computer.

And yes, any usage of system() leads to unportable code, as the parameter is passed to the shell that owns your process.

Having pausing-code in your source code sooner or later causes hassles:

  • someone forgets to delete the pausing code before checking in
    • now all working mates have to wonder why the app does not close anymore
    • version history is tainted
  • #define is hell
  • it's annoying to anyone who runs your code from the console
  • it's very, very, very annoying when trying to start and end your program from within a script; quadly annoying if your program is part of a pipeline in the shell, because if the program does not end, the shell script or pipeline won't, too

Instead, explore your IDE. It probably has an option not to close the console window after running. If not, it's a great justification to you as a developer worth her/his money to always have a console window open nearby.

Alternatively, you can make this a program option, but I personally have never seen a program with an option --keep-alive-when-dead.

Moral of the story: This is the user's problem, and not the program's problem. Don't taint your code.

Solution 2 - C++

If you want to write portable C++ code, then I'd suggest using cin.get().

system("PAUSE") works on Windows, since it requires the execution of a console command named "PAUSE". But I'm not sure that other operating systems like Linux or other Unix derivatives support that. So that tends to be non-portable.

Since C++ already offers cin.get(), I see no compelling reason to use C getch().

Solution 3 - C++

The best way depends a lot on the platform(s) being targeted, debug vs. release usage etc.

I don't think there is one best way, but to "force" a wait on enter type scenario in a fairly generic way, especially when debugging (typically this is either compiled in or out based on NDEBUG or _DEBUG), you could try std::getline as follows

inline void wait_on_enter()
{
	std::string dummy;
	std::cout << "Enter to continue..." << std::endl;
	std::getline(std::cin, dummy);
}

With our without the "enter to continue", as needed.

Solution 4 - C++

> Which is best way to pause the console in C++ programs?

system("pause"); and getch(); (which comes from the DOS world, IIRC) are both unportable.

> Is cin.get() is better to use to pause console?

As the only one portable and standard option, I would say it is, but I personally believe one should not write interactive console programs, i.e. programs which actually pause the console or prompt for input (unless there is a really good reason for that, because that makes shell scripting much harder). Console programs should interact with the user via command line arguments (or at least that kind of interaction should be the default one).

Just in case you need pausing the program for the my-program-is-launched-from-the-IDE-and-immediately-closed-but-I-don't-have-enough-time-to-see-the-result reason — don't do that. Just configure your IDE or launch console programs right from the console.

Solution 5 - C++

There is no good way to do that, but you should use portable solution, so avoid system() calls, in your case you could use cin.get() or getch() as you mentioned in your question, also there is one advice. Make all pauses controlled by one (or very few) preprocessor definitions.

For example:

Somewhere in global file:

#define USE_PAUSES
#ifndef _DEBUG    //I asume you have _DEBUG definition for debug and don't have it for release build
#undef USE_PAUSES
#endif

Somewhere in code

#ifdef USE_PAUSES
cin.get();
#endif

This is not universal advice, but you should protect yourself from putting pauses in release builds and these should have easy control, my mentioned global file may not be so global, because changes in that may cause really long compilation.

Solution 6 - C++

(My answer is partially based on that from Yoank, and partially on a comment by Justin Time on another question.)

cout << endl << "Press <Enter> to continue...";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();

Solution 7 - C++

system("pause") is a perfectly valid way of pausing a console in Windows, "pause" is actually a system command that windows recognizes and as such, you never have to worry about it calling a program by the same name, or anything like that. The idea of system("pause") being dangerous in that regard is myth.

However this is not the case outside of windows, so it is best to use the preprocessor to delineate between the platforms.

#ifdef _WIN32 || _WIN64
if(argc <= 1) // optional, prevents pausing if the user runs "program.exe -lol"
	system("pause");
#endif

You can add preprocessor branches for pausing in other platforms, as you see fit... But in my opinion, giving it to Windows is more than enough, as Linux users are more likely to run things from a console anyway. Additionally, if you have a command line parser, you can shutdown the pause with certain arguments. (The condition in the code snippet you see, is literally "any argument at all" as just a lazy example.)

Solution 8 - C++

I just want to add that there is a way to get what you want, but it will require to use some a third party library (or that you write the platform dependent code yourself).

As far as I'm concerned, the biggest drawback with cin is that you are required to hit Return, and not just any key.

Assuming you had a key-listener you could quite easily write a function that waits for the user to hit any key. However finding a platform independent key listener is no trivial task, and will most likely require you to load parts of a larger library.

I am thinking something along the lines of:

char wait_for_key() {
    int key;
    while ( ! (key == key_pressed(ANY)) ) {
          this_thread::yield();
    }
    return convert_virtual_key_to_char(key);
}

The actual function would obviously be quite different from what I wrote, depending on the library you use.

I know the following libraries have keylisteners (Feel free to add more in an edit if you know of any.):

Solution 9 - C++

I always used a couple lines of code which clear the input stream of any characters and then wait for input to ignore.

Something like:

void pause() {
    cin.clear();
    cout << endl << "Press any key to continue...";
    cin.ignore();
}

And then any time I need it in the program I have my own pause(); function, without the overhead of a system pause. This is only really an issue when writing console programs that you want to stay open or stay fixated on a certain point though.

Solution 10 - C++

This works for me.

void pause()
{
	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	std::string dummy;
	std::cout << "Press any key to continue . . .";
	std::getline(std::cin, dummy);
}

Solution 11 - C++

Late response, but I think it will help others.

Part of imitating system("pause") is imitating what it asks the user to do: "Press any key to continue . . . " So, we need something that does not wait for simply a return as std::cin.get() would do. Even getch() has its problems when used twice (the second time call has been noticed to skip pausing generally if it's immediately paused again afterwards on the same key press). I think it has to do with the input buffer. System("pause") is usually not recommended, but we still need something to imitate what users might already expect. I prefer getch() because it doesn't echo to the screen, and it works dynamically.

The solution is to do the following using a do-while loop:

void Console::pause()
{ 
	int ch = 0;

	std::cout << "\nPress any key to continue . . . ";
	 
	do {
		ch = getch();
	} while (ch != 0);

	std::cout << std::endl;
} 

Now it waits for the user to press any key. If it's used twice, it waits for the user again instead of skipping.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDestructorView Question on Stackoverflow
Solution 1 - C++Sebastian MachView Answer on Stackoverflow
Solution 2 - C++Mr.C64View Answer on Stackoverflow
Solution 3 - C++NiallView Answer on Stackoverflow
Solution 4 - C++namelessView Answer on Stackoverflow
Solution 5 - C++ST3View Answer on Stackoverflow
Solution 6 - C++Marc.2377View Answer on Stackoverflow
Solution 7 - C++Anne QuinnView Answer on Stackoverflow
Solution 8 - C++Stian SvedenborgView Answer on Stackoverflow
Solution 9 - C++Esoteric EricView Answer on Stackoverflow
Solution 10 - C++YoankView Answer on Stackoverflow
Solution 11 - C++BobView Answer on Stackoverflow