Search code examples
ckbhit

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;
}

I noticed the kbhit() function was going weird in the game I was making so I tried this code. It printed 0 at the beginning, when the key was not pressed. 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?


Solution

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

    kbhit() returns zero, if any key is not pressed.


    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?

    Reason: kbhit() is buffered function. So, every keystroke will be sent to the buffer, and processed sequentially. If you donot clear the buffer, same output will be printed by printf function. You can flush the buffer to remove the keystroke or use getch.

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