Skip to content
Related Articles

Related Articles

Improve Article

kbhit in C language

  • Difficulty Level : Easy
  • Last Updated : 06 Jun, 2020
Geek Week

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.




// 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




// 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

This article is contributed by Nishu Singh 1. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.



My Personal Notes arrow_drop_up
Recommended Articles
Page :