-
Need further guidance
Hi guys, I'm new to this forum and to C programming as well. I need some guidance from you seniors to help me implement my concept in C programming. What I'm trying to do is using C programming to read which key on the keyboard is pressed and then to check whether the key is (lets just say) "r" or not. If it is "r", the program will proceed with stopping my robot's process. So what I have now is listed below. Please give me further guidance. Thanks in advance :)
Code:
#include <stdio.h>
#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;
}
int main(void)
{
while(!kbhit())
printf("You pressed '%c'!\n", getchar());
return 0;
}
-
So what's stopping you?
I mean, if you've got that far, it's dead easy to compare the result with say 'r'
-
I'm not sure about which command to use :S
-
getchar returns an integer. One of the things that integer can represent is the constant EOF, which signals the end of the file, or input stream. Your code is already reading in a character and checking to see if it was that specific character. The getchar function can also return the ASCII (it's usually ASCII, but keep in mind that it could be whatever encoding your machine happens to use - the C standard doesn't specify an encoding) value of the key that was pressed. You can represent the value for a particular character in C, by something like, 'r'. So if the output of the function matches that value, you know what key they hit.
edit: I'm guessing you didn't write the code you posted yourself. Make sure you say that in future. It's very confusing and/or inconsistent when someone posts code that does 'x', and they're asking how to do 'x'. If people think you're trying to get out of doing homework, they're less likely to help.