Reputation: 14448
Which is best way to pause the console in C++ programs?
cin.get()
system("pause")
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?
Upvotes: 71
Views: 327162
Reputation: 13030
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.)
Upvotes: 2
Reputation: 39109
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:
#define
is hellInstead, 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.
Upvotes: 72
Reputation: 327
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.
Upvotes: 0
Reputation: 8764
(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();
Upvotes: 1
Reputation: 7
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);
}
Upvotes: 0
Reputation: 1
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.
Upvotes: 0
Reputation: 8946
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.
Upvotes: 1
Reputation: 30624
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.
Upvotes: 5
Reputation: 1979
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.
Upvotes: 3
Reputation: 1825
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.):
Upvotes: 0
Reputation: 43044
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()
.
Upvotes: 24