我正在尝试在 Windows 终端应用程序(仅限 Windows,抱歉!)上获得非阻塞 I/O。
如果我想要一个很短的输入时间,用户可以按下一个按钮,但如果他没有按下按钮,输入就会停止,程序会继续运行怎么办?
例如:
一个计时器,从 1 开始计数,直到用户按下某个键时停止: 我应该有一个 while 循环,但如果我执行 getch 或 getchar 函数,它会停止程序,对吗?
我知道我可以使用 kbhit(); ,但对于我试图制作的“程序”,我需要知道输入,而不仅仅是如果有输入! 是否有任何简单的函数可以让我像键盘缓冲区中的最后一个键一样阅读?
最佳答案
来自documentation for _kbhit()
:
The
_kbhit
function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call_getch
or_getche
to get the keystroke.
所以,在你的循环中:
while (true) {
// ...
if (_kbhit()) {
char c = _getch();
// act on character c in whatever way you want
}
}
因此,您仍然可以使用 _getch()
,但将其使用限制在 _kbhit()
表示有等待的情况下。这样它就不会阻塞。
关于c - c中的非阻塞i/o? ( window ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21294713/