Open In App

kbhit in C language

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

kbhit() functionality is basically stand for the Keyboard Hit. This function is deals with keyboard pressing 

kbhit() is present in conio.h and used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file “conio.h”. If a key has been pressed then it returns a non zero value otherwise returns zero. 

CPP




// C++ program to demonstrate use of kbhit()
#include <iostream.h>
#include <conio.h>
 
int main()
{
    while (!kbhit())
        printf("Press a key\n");
 
    return 0;
}


Output:

"Press a key" will keep printing on the 
console until the user presses a key on the keyboard.

Note : kbhit() is not a standard library function and should be avoided. Program to fetch the pressed key using kbhit 

CPP




// C++ program to fetch key pressed using
// kbhit()
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    char ch;
    while (1) {
 
        if ( kbhit() ) {
 
            // Stores the pressed key in ch
            ch = getch();
 
            // Terminates the loop
            // when escape is pressed
            if (int(ch) == 27)
                break;
 
            cout << "\nKey pressed= " << ch;
        }
    }
    return 0;
}


Output:

Prints all the keys that will be pressed on
 the keyboard until the user presses Escape key

C




#include <stdio.h>
// include conio.h file for kbhit function
#include <conio.h>
main()
{
    // declare variable
    char ch;
    printf("Enter key ESC to exit \n");
    // define infinite loop for taking keys
    while (1) {
        if (kbhit) {
            // fetch typed character into ch
            ch = getch();
            if ((int)ch == 27)
                // when esc button is pressed, then it will exit from loop
                break;
            printf("You have entered : %c\n", ch);
        }
    }
}


Output :
Enter key ESC to exit
You have entered : i
You have entered : P
You have entered : S
You have entered : w
You have entered : 7
You have entered : /
You have entered : *
You have entered : +



Last Updated : 07 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads