NoN*_*eY0 4 c keyboard getchar
因此,对于键盘上的向上键,我得到27,令人惊讶的是,对于向下键我也得到27.我需要我的程序在向上和向下键上表现不同,我似乎无法弄明白.我正在使用Linux,需要它才能用于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");
}
}
Run Code Online (Sandbox Code Playgroud)
这27意味着您将获得箭头的ANSI转义序列.它们将是三个字符的序列:27,91,然后是65,66,67,68(IIRC),用于向上,向下,向右,向左.如果您27从通话中获得getchar(),则再拨打两次以获取91确定按箭头键的数字和数字.
正如其他人提到的,这是特定于平台的,但您可能并不在意.
这是程序,它被编写为使用 ncurses 库,并显示按下的箭头键。
#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;
}
Run Code Online (Sandbox Code Playgroud)
编译时,您必须链接到 ncurses 库。
gcc main.c -lncurses
Run Code Online (Sandbox Code Playgroud)
这是一个帮助您开始使用 ncurses的教程。
您将按下的键与按下时生成的字符混淆了。您希望按下 Shift 键时得到一个字符吗?试试这个程序:
#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);
}
Run Code Online (Sandbox Code Playgroud)
尝试点击向上箭头,然后输入。然后尝试点击向下箭头,然后输入。你会发现按键到字符的转换并不简单。