C kbhit() returns 1 即使没有按下键

C kbhit() returns 1 even when key is not pressed

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

int main()
{
    while(1)
    {
        printf("%d", kbhit());
        Sleep(100);
    }
    return 0;
}

我注意到 kbhit() 函数在我制作的游戏中变得很奇怪,所以我尝试了这段代码。 当键未被按下时,它在开始时打印 0。然后我按下一个键,它打印了 1,即使我停止按下任何键,它仍然继续打印 1。为什么会这样?

It printed 0 at the beginning, when the key was not pressed

kbhit() returns 零,如果没有按下任何键。


Then I pressed a key and it printed 1, and continued to print 1 even after I stopped pressing any keys. Why is this happening?

原因: kbhit()是缓冲函数。因此,每次击键都会被发送到缓冲区,并按顺序进行处理。如果不清除缓冲区,printf 函数将打印相同的输出。您可以刷新缓冲区以删除击键或使用 getch.

参考:https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/kbhit?view=msvc-160