C programming if the key is pressed without stopping the program

as you know, when using getch () in the application windows, they are waiting for you until you press the key,

how can I read the key without freezing the program, for example:

void main(){ char c; while(1){ printf("hello\n"); if (c=getch()) { . . . } } 

thanks.

+4
source share
2 answers

You can use kbhit() to check if a key is pressed:

 #include <stdio.h> #include <conio.h> /* getch() and kbhit() */ int main() { char c; for(;;){ printf("hello\n"); if(kbhit()){ c = getch(); printf("%c\n", c); } } return 0; } 

Further information here: http://www.programmingsimplified.com/c/conio.h/kbhit

+8
source

I needed similar functionality in a console application on Linux, but Linux does not provide the kbhit function. When searching on Google, I found an implementation in

http://www.flipcode.com/archives/_kbhit_for_Linux.shtml

0
source

All Articles