Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c programming check if key pressed without stopping program

Tags:

c

windows

as you know, when using getch() in windows, the applications waits for you until you press a key,

how can i read a key without freezing the program , example :

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

thank you.

like image 676
Ouerghi Yassine Avatar asked Nov 25 '12 01:11

Ouerghi Yassine


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;
}

More info here: http://www.programmingsimplified.com/c/conio.h/kbhit

like image 139
emil Avatar answered Sep 23 '22 18:09

emil


I needed similar functionality in a console application in Linux, but Linux don't provide kbhit function. On searching Google, I found an implementation at -

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

like image 34
Harmeet Avatar answered Sep 22 '22 18:09

Harmeet