1
#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?

CTTG
  • 27
  • 1
  • 7
  • 2
    I'm not familiar with the DOS api, but I would imagine you'd have to flush the input buffer by reading the input with `getch()` while `kbhit()` returns true. – vmt Dec 24 '20 at 05:36
  • 2
    https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/kbhit?view=msvc-160 `If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke.` – Retired Ninja Dec 24 '20 at 05:50
  • For a game, why use buffered keyboard input at all? Consider, just calling [GetKeyboardState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getkeyboardstate) on every frame and evaluate the keys you care about. When I worked in a game studio (ages ago), that's what we used. Or [GetAsyncKeyState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate) if your game isn't pumping windows messages. – selbie Dec 24 '20 at 06:08

1 Answers1

4

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

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26