【发布时间】:2015-12-13 08:29:19
【问题描述】:
我希望我的控制台应用程序停止并等待用户按键。如果在有限的时间后没有键盘输入,假设 2 秒,执行应该恢复。
我知道没有解决方案可以在所有实现中移植,但至少有简单的解决方案吗?
this one 或 this one 之类的一些帖子处理类似问题,但它们似乎没有为该特定问题提供答案。
如果我可以使用 ncurses(我不能),我会使用 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;
}
【问题讨论】:
-
那里的解决方案似乎有点复杂,更重要的是,其他人认为这可能行不通。我想使用
std::thread和std::cin的组合来同时捕获输入和计算时间,但我不确定这如何工作。