0

How can i make a function that stops the program when a key is pressed?(the function needs to run as a thread).I tried this but doesn't work

  _getch() == true;

  if(_getch() == true){

    exit(0);

  }
  • 4
    It is operating system specific. The C++11 standard does not know about the keyboard. On Linux read [the tty demystified](http://www.linusakesson.net/programming/tty/) and consider using [ncurses](http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/). BTW `_getch` is not a standard documented function – Basile Starynkevitch Mar 10 '18 at 08:23
  • Possible duplicate: https://stackoverflow.com/questions/4293355/how-to-detect-key-presses-in-a-linux-c-gui-program-without-prompting-the-user – Kumar Roshan Mehta Mar 10 '18 at 08:38

2 Answers2

1

You can use the ncurses library,

#include <ncurses.h>
... 
initscr();          /* Start curses mode   */
getch();            /* Wait for user input */
endwin();           /* End curses mode     */
...

You can find the documentation related to it at the NCURSES Programming HOWTO

0

The answer exists at askubuntu.

The following works on windows and linux/unix:

#include <iostream>
...
std::cout << "Press \'Return\' to end." << std::endl;
cin.sync(); // instead of flush()
std::cin.get();

The first std::cin.sync() clears the input que, the next command waits for an input.

Smit Ycyken
  • 1,189
  • 1
  • 11
  • 25