Ascii value of Enter Key in C - Unix [closed]
I would like to print "You have pressed Enter key" when ever user hits Enter Key. Please help me write this in C Program.
Regards, Kiran.
#include<stdio.h>
int
main(int argc, char *argv[])
{
int ch;
while(1)
{
ch = fgetc(stdin);
if (ch == 10) {
fprintf(stdout, "You have pressed the enter key\n");
}
}
}
notes: you may want to set your terminal to raw mode, and this vary from OS to OS. in this case, the terminal may be set by default to cooked mode, so the terminal driver from the os might actually not give you a character at the time until you actually press the enter key.
to change your terminal to raw mode you might need to check the ioctl()'s needed for your particular OS (if you specify which one, i might be able to help)
The enter key itself doesn't have an ASCII character, it has a scan code.
'\n'
is the ASCII line-ending for UNIX, "\r\n"
on Windows, and '\r'
on Mac.
The scan code is a hardware-specific number which gets translated by the application into a character.
Where do you capture the key press?
It depends on your terminal input modes, particularly on ICRNL
. See the termios(3) manpage.
Assuming you mean a CARRIAGE RETURN, it is ASCII 13 or Hexadecimal 0x0D (hence my username 0A0D). If you mean LINE FEED, it is ASCII 10 or Hexadecimal 0x0A. I will let you enhance your question more before I answer further.
Whenever you want to get an ascii value of anything do a "getche()" it will echo a characher pressed. So you run the program and press enter and get the ascii value.
For enter and escape its 27 & 13 .. don't remember which belongs to which
If you don't want to use a magic number you can use a character: C knows it as '\r'
精彩评论