【发布时间】:2015-01-04 14:21:26
【问题描述】:
首先,对不起我的英语不好。我正在使用 windows.h 中包含的 GetTickCount() 函数和 conio.h 中包含的 getch() 函数。
我真正想要的是给用户一个输入字符的时间限制。如果超过时间限制,程序继续执行,跳过等待用户输入字符。
char ch='A';
DWORD start_time, check_time;
start_time=GetTickCount();
check_time=start+500; //GetTickCount returns time in miliseconds, so I add 500 to wait input for half a second.
while (check_time>GetTickCount()) {
ch=getchar();
}
//do stuff with char with initial value of 'A' if user didn't enter another char during 500ms of wait.
但是 getchar() 会停止执行程序并无限期地等待用户输入 char。是否有一个简单的解决方案可以绕过此等待,并在 500 毫秒过去后继续?
编辑:
根据您的提示,我写了这个并且它有效!谢谢各位!
while (!kbhit()&&(check_time>GetTickCount()))
{
if (kbhit())
{
ch=getch();
break;
}
}
【问题讨论】:
-
你必须使用另一个函数来读取标准输入,比如ioctl,也可以看到stackoverflow.com/questions/10004895/…
-
在 unix 上,你有 select() 来完成这项工作。在 Windows 上,我不知道。
-
This link 展示了如何做到这一点
-
@CharlieBurns -
GetAsyncKeyState()在 Windows 中用于检测特定键。不确定它在这里是否完美,但非常适合设置特定键,查看它何时被击中。 -
在你的链接中有一个叫做 kbdhit() 的东西可能对他有用。
标签: c windows input time limit