You need conio.h for your requirement. It determines that kbhit () and getch () are waiting for keyboard input.
When kbhit () is called, it checks the keyboard buffer and returns a nonzero value if the buffer has any keystroke, otherwise 0 is returned.
Conio.h is used by MSDOS compilers and is not part of the standard C (ISO) libraries. It is also not defined in POSIX.
#include<stdio.h> #include<conio.h> int main() { while(1) { while(!kbhit()) { //works continuously until interrupted by keyboard input. printf("M Tired. Break Me\n"); } getch(); } return 0; }
For linux, you can use the following snippet to implement kbhit () using fnctl () from fnctl.h to process signals:
#include <termios.h> #include <unistd.h> #include <fcntl.h> int kbhit(void) { struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if(ch != EOF) { ungetc(ch, stdin); return 1; } return 0; }
user4702672
source share