gpt4 book ai didi

c - 如何在C中设置用户输入字符的时间限制?

转载 作者:可可西里 更新时间:2023-11-01 10:05:46 25 4
gpt4 key购买 nike

首先,抱歉我的英语不好。我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com