C++ How to wait for keyboard input for a limited time

末鹿安然 提交于 2019-12-13 01:37:28

问题


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;
}

回答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.



来源:https://stackoverflow.com/questions/32613912/c-how-to-wait-for-keyboard-input-for-a-limited-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!