I found a solution ,but I have to push a key I want twice instead of once.
Here is the code and I think the problem is to getch().
Can you help me to fix this problem(I want to push a button once and not twice).
Code:
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/select.h>
int kbhit(void);
int getch(void);
int kbhit(void)
{
struct timeval tv;
fd_set read_fd;
tv.tv_sec=0;
tv.tv_usec=0;
FD_ZERO(&read_fd);
FD_SET(0,&read_fd);
if(select(1, &read_fd,NULL, NULL, &tv) == -1)
return 0;
if(FD_ISSET(0,&read_fd))
return 1;
return 0;
}
int getch(void) {
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
int main(){
int a = 1;
while(a == 1){
if(kbhit() == 0){
getch();
printf("%c is pressed\n",getch());
}
}
return 0;
}
For example, if I press 'a' and then again 'a' ,then I recieve -> a is pressed.
But I want to press 'a' only once to recieve -> a is pressed.
I need your help.
Thanks in advance...