C library function to check the keypress from keyboard( in linux )
c
Solution
`getchar()` from the Header file `stdio.h` returns the next character from stdin. That's probably what you're searching for.
The following code will output the first char from the stdin stream:
#include <stdio.h>
int main (int argc, char **argv){
char c = getchar();
printf("Char: %c", c);
return 0;
}
There are also other functions available to do this without blocking i.e. `kbhit()` and getch() in `conio.h`. But the header file `conio.h` is non-standard and probably not available on your platform if you are using linux.
So you have 2 options:
1.) Using the library ncurses you can use i.e. the function timeout() to define an timeout for the `getch()` function like this:
initscr();
timeout(1000);
char c = getch();
endwin();
printf("Char: %c\n", c);
2.) Implement `kbhit()` by yourself without using ncurses. There is a great expanation here to do so. You would have to measure time by yourself and looping until your timeout is reached. To measure time in C, there are plenty threads here on stackoverflow - you just have to search for it. Then your code would look like this:
while(pastTime() < YOUR_TIMING_CONSTRAINT){
if (kbhit()){
char c = fgetc(stdin);
printf("Char: %c\n", c);
}
}
Problem
Is there any C library function to check the keypress from keyboard( I am working on linux machine ).