'How do I get char directly from keyboard not through buffer?

I am making a game which has a character moves in 4 directions: up, down, left, right corresponding to W,S,A,D on the keyboard. The problem is when using getch() to get input from buffer, it always has a pause time after the first single keypress. For instance, when I hold 'A' button, it acts like: A(a short period of time)AAAAAAAAA.

How do I get rid of that delay time?

Any help would be appreciated.

(Answers in either C or C++ are all acceptable, since I am using graphics.h for this program, which requires C++ to run, but I mainly code in C).


I am using windows 10 64 bits.



Solution 1:[1]

For a non-blocking getch method I personally use this piece of code (in C):

#include <conio.h>

int getch_noblock(){
   return _kbhit() ? _getch() : -1;
}

the _kbhit() method returns 0 if no key are pressed, otherwise returns a number if the keyboard input buffer is not empty.

the _getch() method read a char from the keyboard buffer.

It works only for Windows.

Documentation:

  1. _khbit(): https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/kbhit?view=msvc-170
  2. _getch(): https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-getwch?view=msvc-170

By the way, surfing on the web I found an interesting method, but I've never tried or seen it: https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-nolock-getwch-nolock?view=msvc-170

Solution 2:[2]

getch() already bypasses buffer:

 Prototype
         int _getch(void);  

 Description
         _getch obtains a character  from stdin. Input is unbuffered, and this
         routine  will  return as  soon as  a character is  available  without 
         waiting for a carriage return. The character is not echoed to stdout.
         _getch bypasses the normal buffering done by getchar and getc.

And for your problem, as someone already said, you can use the kbhit() method

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 al366io