#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?
kbhit()returns zero, if any key is not pressed.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 byprintffunction. You can flush the buffer to remove the keystroke or usegetch.Reference : https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/kbhit?view=msvc-160