4

Here is a simple code in C++:

cout << "Press Any Key To Exit...";

What is the code for closing program when user presses any button on keyboard. What should I write after above code? I know I can use cin.ignore(); and if user presses Enter the program will close, But my target is any key.

How to do that?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Inside Man
  • 4,194
  • 12
  • 59
  • 119

4 Answers4

22

You can use getchar or cin.get() to accomplish this, both will block till they can get a character from the console (monitoring keys that don't input into the console leads into the realm of system specific).

Necrolis
  • 25,836
  • 3
  • 63
  • 101
  • 4
    I believe those two functions behave differently depending on the terminal emulator used. They still require the enter key to be pressed here (xterm). – howard Feb 19 '12 at 08:34
7

Try this: system("pause"); It will hold until any key is pressed.

EDIT: please read comments below before deciding on this alternative

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
4

You can use the ncurses library to do this. The downside to this solution is that you won't be able to use cout for outputting anymore.

#include <ncurses.h>
int main()
{
    initscr();
    printw("Press Any Key To Exit...");
    getch();
    endwin();
}

Be sure to -lncurses when compiling

howard
  • 644
  • 2
  • 7
  • 15
3

getch(), getche(), system("pause"), exit(0)...should work.

Shashank Kadne
  • 7,993
  • 6
  • 41
  • 54
  • 2
    Don't use system("pause"). It is slow. It is disliked by antivirus software. It is OS-dependent. And it is a massively huge, gaping, security hole. – Sudhir Bastakoti Feb 19 '12 at 08:03
  • 7
    @Sudhir: Most of that comment is true, but the first sentence is nonsense. How can a pause be "slow"? – Cody Gray - on strike Feb 19 '12 at 09:03
  • @CodyGray Sudhir wants to sound like he knows what he's doing, in other words cool :-) – Igwe Kalu May 13 '13 at 21:43
  • @CodyGray system() fires up new command processor (depending on OS, it could be shell, bash, cmd, ksh... or powershell) and gives it provided command. executed in CURRENT directory. Security hole it is, because one may supply own "pause" program in current directory (which can be adjusted beforehand) which would be run at credentials of original. – Swift - Friday Pie Nov 03 '21 at 12:44