如何在有限的时间内等待键盘输入

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

本文关键字:等待 键盘 输入 时间      更新时间:2023-10-16

我希望我的控制台应用程序停止并等待用户按下一个键。如果在限定时间后没有键盘输入,假设是2秒,执行将恢复。

我知道没有解决方案可以在所有实现中移植,但是至少有简单的解决方案吗?

像这篇或这篇这样的文章处理类似的问题,但他们似乎没有提供一个具体问题的答案。

如果我可以使用护士(我不能),我会使用getch()timeout()函数做这样的事情:

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

这样做的一种方法是使用低级read()(假设您在Posix上)与超时信号耦合在一起。由于read()将在信号处理后以EINTR退出,因此您将知道已达到超时。