簡體   English   中英

C ++ _getch()讀取多個值

[英]C++ _getch() read multiple values

#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77

int main()
{
    int c = 0;
    while (c != 27)    //esc key code
    {
        c = 0;

        switch (c = _getch()) 
        {
        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 << "Left" << endl;  // key left
            break;
        case KEY_RIGHT:
            cout << endl << "Right" << endl;  // key right
            break;
        default:
            cout << endl << "null" << endl;
            break;
        }

    }
    return 0;
}

輸出應為

Up
Down
Left
Right

但是我得到的是

null
Up
null
Down
null
Left
null
Right

基於輸出,該程序將讀取其他鍵代碼,我不知道在讀取實際鍵代碼之前,我之前沒有任何cin是什么,為什么? 有什么辦法嗎?

如果您選擇閱讀精美的手冊 ,則會遇到以下聲明:

讀取功能鍵或箭頭鍵時,每個功能必須調用兩次; 第一次調用返回0或0xE0 ,第二次調用返回實際的鍵碼。

這樣一來,您就可以知道72何時表示向上箭頭,何時是字母H (恰好具有ASCII碼72)。

在此處輸入圖片說明

所做的更改:

我從switch語句中刪除了default 這導致了空打印。

此外,我還添加了kbhit()#define KEY_ESC 27 ,並將getch()移到switch語句的#define KEY_ESC 27

#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
#define KEY_ESC 27

#include <conio.h>
#include <stdio.h>
#include <windows.h>
#include <iostream>     
using namespace std;

int main()
{

    int c = 0;

    while ( c!= KEY_ESC )    //esc key code is 27
    {
        if (kbhit()) {
            c = getch();

                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 << "Left" << endl;  // key left
                    break;
                case KEY_RIGHT:
                    cout << endl << "Right" << endl;  // key right
                    break;

                }//switch

        }//if

    }//while

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM