1

I want my console application to stop and wait for the user to press a key. If there is no keyboard input after a limited time, let us say 2 seconds, execution should resume.

I know that no solution will be portable across all implementations, but are there at least simple solutions?

Some posts like this one or this one deal with similar issues, but they don’t seem to offer an answer to that specific problem.

If I could use ncurses (which I can't), I would do something like this using the getch() and timeout() functions:

#include <ncurses.h>
int main()
{
    initscr();          // Start curses mode
    cbreak();           // Turn off line buffering
    timeout(2000);      // Wait 2000 ms for user input
    while (true) {
        addstr("You have 2 sec. to press 'q', otherwise ...\n");
        refresh();
        int inKey = getch();
        if (inKey == 'q') break;
    }
    endwin();
    return 0;
}
Community
  • 1
  • 1
CookieMan
  • 11
  • 2
  • 1
    possible duplicate of [How to use a timer in C++ to force input within a given time?](http://stackoverflow.com/questions/28944972/how-to-use-a-timer-in-c-to-force-input-within-a-given-time) – NathanOliver Sep 16 '15 at 16:28
  • The solution there seems a bit complicated and, more importantly, other people are suggesting this may not work. I though about using a combinaison of `std::thread` and `std::cin` to capture input and calculate time simultaneously, but I am not sure how this could work. – CookieMan Sep 16 '15 at 16:54

1 Answers1

1

One way of doing this would be to use low-level read() (assuming you are on Posix) coupled together with timeout signal. Since read() will exit with EINTR after signal processing, you'd know you reached the timeout.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • OK, thanks, I will look into that. This means that this solution would at least work on POSIX compliant systems. – CookieMan Sep 16 '15 at 16:50
  • Low-level read plus poll() or select() on STDIN handle, with a timeout argument other than infinity? – cardiff space man Sep 16 '15 at 17:23
  • @cardiffspaceman, polls/selects usually do not work on stdin, as it considered to be 'immediately available' and poll always returns that the descriptior can be read. – SergeyA Sep 16 '15 at 17:32
  • @SergeyA In my test it worked. It's what I've used in a few casual programs, because I'm used to using poll() to detect input in production code with slightly different I/O such as sockets and character drivers. The OP's immediate need is of course well handled by your answer. – cardiff space man Sep 16 '15 at 20:22
  • @cardiffspaceman, sockets and character drivers are not files, so that is different. Having said that, I fully trust you that on your system you could poll on stdin – SergeyA Sep 16 '15 at 20:42