Using kbhit in C and C++

While programming in C/C++, many a times we need to do something till the user presses a key and then decide on the further course of action in the program based upon the key input. Such a logic or program flow can be implemented using a very simple function “kbhit()”.

We are going to explain the use of the same here in following few lines.

The funciton prototype is
int kbhit();

Thus, as we see the function accepts no argument and returns an integer value. This return type remains ‘0’ (zero) till the user does not presses a key and becomes non-zero as soon as the user presses a key.

Now, if we also want to know which key the user has pressed, we have to use the getch() function alongwith kbhit() function.

A very simple code snippet showing the use of both is shown below:-

while (!kbhit())
//do cool processing here in this loop, which has to continue happening till user presses a key
//Now the user has pressed a key
//To know which key we do following
int ch; //it can be char ch; also as u like it
//now we have the user input in the variable ch
//we can decide further course of action based upon value in ch
//like as follows
if (ch==89)
//we do something if user pressed 'Y'
// note that 89 is ASCII code for 'Y'
//user did not press 'Y'
//so we do something else

We have shown use of if statement here, while we can use any other conditional statements like while or do..while, case etc with ch depending upon our needs.

Keep on doing cool programming, as we say programming is an “Art of playing with logic”…..

5 thoughts on “Using kbhit in C and C++

Leave a Reply

You may also connect using:
login to using facebook