Sunday 8 December 2013

Detect Key-Press Without Pausing Program Execution: kbhit()

kbhit() allows us to keep the program going as it looks for a keypress.

getch(), getche() and getchar() all let us accept keyboard input, but the program will pause while it waits for that key hit.

kbhit() can be used effectively with if/else to get the keyhit without pausing the program. That's what I used for the snake game in my previous post. It let me keep the snake going as it was also 'keyboard aware' at the same time. You have to include conio.h to use kbhit().

The comments in the program will help explain it better:

#include <stdio.h>
#include <conio.h>

int main()
{
    char c='N'; //N is assigned to c

    for(;;) //infinite loop
    {
        printf("%c\t",c); //N is printed over and over
        if(kbhit()) //until a key is hit, the keyvalue is stored in the buffer
        {
            c=getch(); //c is fed the value from the buffer. The program does not pause here
            printf("%c",c); //print the key
            break; //break the loop
        }
    }
    getch(); //yes, the program does pause here.
    return 0;
}