作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
首先,抱歉我的英语不好。我正在使用 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() 停止执行程序并无限期地等待用户输入字符。是否有一种简单的解决方案可以绕过此等待,并在 500 毫秒过去后继续?
编辑:
根据您的提示,我写了这个并且它有效!谢谢大家!
while (!kbhit()&&(check_time>GetTickCount()))
{
if (kbhit())
{
ch=getch();
break;
}
}
最佳答案
正如 Charlie Burns 所提议的那样,conio
中的 kbhit
函数完全符合您的要求:它看起来像是按下了一个键。
你可以这样做:
DWORD start_time, check_time;
start_time=GetTickTime();
check_time=start+500; //GetTickTime returns time in miliseconds, so I add 500 to wait input for half a second.
char ch = 0;
char hit =0
while (check_time>GetTickTime()) {
if (_kbhit()) {
hit = 1;
ch = _getch();
if (ch == 0) ch = _getch() // an arrow key was pressed
break;
}
}
// if hit == 0 we got a timout, else ch is the code of the key
当心:未经测试...
关于c - 如何在C中设置用户输入字符的时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26807231/
我是一名优秀的程序员,十分优秀!