Is there a way to pause like system("pause")?

2k views Asked by At

I've been looking for this on the internet for soooooo long. Is there a way you can press any key and it immediately stops the pause and carries on with executing the code but it doesn't show up the key you pressed on the screen (like system("pause"))?

People said cin.get() and stuff like that, however, if I use that, I have to press any key AND it displays on the screen and you have to press enter after that.

3

There are 3 answers

4
Some programmer dude On

Since you're referencing system("pause") I guess you're using Windows, then you can use _getch to wait for any key.

1
Cheers and hth. - Alf On

Joachim Pileborg has already mentioned _getch as a Windows-specific technical solution.

However, that's a solution looking for a problem … because there's really no problem.

To see the last output from your console program, you can use any of these methods:

  • Run the program from the command line, e.g. an instance of Windows' standard [cmd.exe] command interpreter.

  • Run the program from an IDE, such that it stops at the end. E.g. in Visual Studio just use [Ctrl F5].

  • Run the program in a debugger, with a breakpoint on the closing } of main. E.g. in Visual Studio, add that breakpoint and run via keypress [F5].

Especially when you try the first bullet point, you will notice that having a _getch or system( "pause" ) or such at the end of the program, has no advantage and can be quite annoying!

0
Dietmar Kühl On

I don't know about Windows (where apparently _getch() is the way to go) but on UNIXes you can set the standard input stream (file descriptor 0) into non-canonical mode using tcgetattr() and tcsetattr() to get the key immediately. To suppress the key presses from showing up, you'll need to also disable echoing:

termios old_tio, new_tio;
int rc = tcgetattr(0,&old_tio);
new_tio=old_tio;
new_tio.c_lflag &=(~ICANON & ~ECHO);
rc = tcsetattr(0,TCSANOW,&new_tio);

std::string value;
if (std::cin >> value) {
    std::cout << "value='" << value << "'\n";
}

rc = tcsetattr(0,TCSANOW,&old_tio);

This code

  1. first gets the current state of the terminal flags
  2. clears the ICANON and ECHO flags
  3. read hidden input (in this case a string but it can be an individual key, too)
  4. restores the original settings

There is, unfortunately, no portable way of dealing with these setting, i.e., you will need to resort to platform specific uses. I think the use of tcgetattr() and tcsetattr() is applicable to POSIX systems, though.