C++ — 使用 getch() 进行箭头键按下检测会莫名其妙地打印一些单词

Loq*_*oqz 3 c++ getch switch-statement

我有一个简单的程序可以检测用户按下箭头键,但我有两个问题。但首先,这是代码:

#include <iostream>
#include <conio.h>
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 77
#define KEY_RIGHT 75

using namespace std;

int main()
{
    while(1)
    {
        char c = getch();
        cout << "Hello";
        switch(c) {
        case KEY_UP:
            cout << endl << "Up" << endl;//key up
            break;
        case KEY_DOWN:
            cout << endl << "Down" << endl;   // key down
            break;
        case KEY_LEFT:
            cout << endl << "Right" << endl;  // key right
            break;
        case KEY_RIGHT:
            cout << endl << "Left" << endl;  // key left
            break;
        default:
            cout << endl << "NULL" << endl;  // any other key
            break;
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题 1:每当我按任意箭头键时,为什么它会打印两次“Hello”?

问题 2:每当我按下任何箭头或非箭头键时,它都会打印默认的 switch 大小写“NULL”,这应该仅适用于非箭头键。为什么是这样?

谢谢

Jos*_*ley 5

当使用conio和读取键时getch,为了能够处理特殊键(箭头键、功能键),同时仍将其返回值放入 a 中chargetch将特殊键作为两个char序列返回。第一个调用返回0(或0xe0取决于您使用的 C++ 实现),而第二个调用返回特殊键的代码。(否则,您的KEY_DOWN- ASCII 80 - 本身就是“P”。)

MSDN 有更多信息。

将所有这些放在一起的一种方法如下:

char c = getch();
if (c == 0) {
    switch(getch()) {
        // special KEY_ handling here
        case KEY_UP:
            break;
    }
} else {
    switch(c) {
        // normal character handling
        case 'a':
            break;
    }
 }
Run Code Online (Sandbox Code Playgroud)