getchar() 为向上和向下箭头键返回相同的值 (27) [英] getchar() returns the same value (27) for up and down arrow keys

查看:32
本文介绍了getchar() 为向上和向下箭头键返回相同的值 (27)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以对于键盘上的向上键,我得到 27,令人惊讶的是,对于向下键,我也得到 27.我需要我的程序在向上和向下键上表现不同,我似乎无法弄清楚.我正在使用 Linux,并且需要它在 Linux 上工作.

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");
    }

} 

推荐答案

27 意味着您正在获取箭头的 ANSI 转义序列.它们将是三个字符序列:27、91,然后是 65、66、67、68 (IIRC) 表示上、下、右、左.如果您通过调用 getchar() 得到 27,则再调用两次以获取 91 和确定箭头的数字键被按下.

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.

这篇关于getchar() 为向上和向下箭头键返回相同的值 (27)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆