C ++如何在有限的时间内等待键盘输入 [英] C++ How to wait for keyboard input for a limited time
问题描述
我希望我的控制台应用程序停止,等待用户按下一个键。如果在有限的时间后没有键盘输入,让我们说2秒钟,执行应该恢复。
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.
如果我可以使用ncurses(我不能),我会做这样使用 getch()
和 timeout()
函数:
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;
}
推荐答案
是使用低电平read()(假设你在Posix上)与超时信号耦合在一起。因为read()将在信号处理后用EINTR退出,你会知道你已经超时了。
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.
这篇关于C ++如何在有限的时间内等待键盘输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!