问题
So for the up key on the keyboard, I get 27, surprisingly for the down key I also get 27. I need my program to behave differently on the up and down key, and I can't seem to figure it out. I am using Linux, and need it to work for Linux.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int c = getchar();
if(c==27)
{
printf("UP");
}
if(c==28)
{
printf("DOWN");
}
}
回答1:
The 27
implies that you're getting ANSI escape sequences for the arrows. They're going to be three-character sequences: 27, 91, and then 65, 66, 67, 68 (IIRC) for up, down, right, left. If you get a 27
from a call to getchar()
, then call it twice more to get the 91
and the number that determines what arrow key was pressed.
As someone else mentioned, this is platform-specific, but you may not care.
回答2:
Here is the program , which is written to use ncurses library , and display the arrow keys pressed.
#include<ncurses.h>
int main()
{
int ch;
/* Curses Initialisations */
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
printw("Press E to Exit\n");
while((ch = getch()) != 'E')
{
switch(ch)
{
case KEY_UP: printw("\nUp Arrow");
break;
case KEY_DOWN: printw("\nDown Arrow");
break;
case KEY_LEFT: printw("\nLeft Arrow");
break;
case KEY_RIGHT: printw("\nRight Arrow");
break;
default:
printw("\nThe pressed key is %c",ch);
}
}
printw("\n\Exiting Now\n");
endwin();
return 0;
}
while compiling , you have to link to the ncurses library.
gcc main.c -lncurses
Here is a tutorial to help you get started with ncurses.
回答3:
Check out the ncurses library at http://www.gnu.org/software/ncurses/. Linking it to your program will enable you to do all sorts of neat stuff with key events. Read up on the documentation and see if you want to use it. It provides exactly the functionality you say you're looking for.
Happy coding!
回答4:
You are confusing keys you press with the characters they generate when pressed. Would you expect to get one character when the shift key is pressed? Try this program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
do
{
int c = getchar();
printf("c=%d\n", c);
}
while (1);
}
Try hitting the up arrow and then enter. Then try hitting the down arrow and then enter. You will see that the conversion of keys to characters is not simple.
来源:https://stackoverflow.com/questions/15306463/getchar-returns-the-same-value-27-for-up-and-down-arrow-keys