C example to use kbhit() function

In this example, we are going to learn about 'kbhit()' function - which is a predefined function of 'conio.h' header file with an example.
By Shamikh Faraz Last updated : March 10, 2024

kbhit() function

kbhit() is a function used to check whether a key is pressed or not. To use 'kbhit' function you must include <conio.h> header file. If a key is pressed then it returns a non zero value, otherwise returns zero.

Example to use kbhit() function

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

int main()
{
    do {
        printf("Press any key to stop loop.\n");
    } while (!kbhit());

    return 0;
}

Output

Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.
Press any key to stop loop.

Till N time, until you don't press any key.

Explanation

Until you don't press any key, the condition in do while loop is true and continuously prints "Press any key to stop loop." When any key is pressed, the condition in do while loop goes false and kbhit() will return a non-zero value. (!(any_non_zero) = 0), so do while loop stops.

C Miscellaneous Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.