gpt4 book ai didi

C 延迟无限循环中的奇怪 kbhit() 行为

转载 作者:行者123 更新时间:2023-12-02 04:39:54 24 4
gpt4 key购买 nike

我一直在用 kbhit() 测试一些东西,发现延迟无限循环的奇怪行为。在此代码示例中,我将循环延迟为每秒运行 30 次。

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>

_Bool IsKeyDown(char c)
{
if(kbhit())
{
char ch1 = getch();
if(ch1 == c)
return 1;
}
return 0;
}

/*
*
*/
int main(int argc, char** argv) {
while(1)
{
if(IsKeyDown('a'))
{
printf("HELLO\n");
}
if(IsKeyDown('b'))
{
printf("HI\n");
}
Sleep(1000 / 30);
}
return (EXIT_SUCCESS);
}

问题是,虽然循环中的第一个 if 语句工作正常,但第二个 if 语句几乎不起作用。如果您在此示例中按住“a”键,则会无限期打印 HELLO。如果您按住“b”键,则几乎不会打印 HI。

为什么会出现这种行为?

最佳答案

发生这种情况是因为您的 IsKeyDownkbhit 时,消耗 缓冲区中的下一个字符会产生副作用返回 true .因为你调用IsKeyDown连续两次,第一次调用“吃掉”了 'b' ,因此当需要运行第二次调用时,缓冲区中没有数据。

您需要重新组织您的代码,以便 IsKeyDown每次循环迭代只调用一次。您的循环应存储其返回值,并将该存储值与您需要的字符(即 'a''b' )进行比较:

int GetKeyDown() {
if(kbhit())
{
return getch();
}
return -1;
}

while(1)
{
int keyDown = GetKeyDown();
if(keyDown == 'a')
{
printf("HELLO\n");
}
if(keyDown == 'b')
{
printf("HI\n");
}
Sleep(1000 / 30);
}

关于C 延迟无限循环中的奇怪 kbhit() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21074310/

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