为什么switch总是运行default?(与休息;包括)

Why does switch always run default? (with break; included)

本文关键字:包括 switch 运行 default 为什么      更新时间:2023-10-16

c++新手尝试在2D数组上制作一个简单的文本游戏

当我使用switch语句时,如下所示。不管发生了什么,它都会输出默认值。

从其他线程和论坛我发现它可能与getch()有关,它返回char以及n

我已经试了一个小时了,但是我解决不了这个问题。我使用getch()的原因是:c++改变了windows中的规范模式(供参考)。

我现在的部分代码:

//Set up game field
generateField();
setPlayerStart();
//printGameInfo(); TO BE MADE
//Start game while loop
int userInput;
do{
    //system("cls"); DISABLED FOR TESTING PURPOSES
    printField();
    userInput = getch();
    switch(userInput){
        case 72:{ //ARROW UP
            cout << "1What" << endl; //ALSO FOR TESTING PURPOSES
            break;
        }
        case 80:{ //ARROW DOWN
            cout << "2What" << endl;
            break;
        }
        case 75:{ //ARROW LEFT
            cout << "3What" << endl;
            break;
        }
        case 77:{ //ARROW RIGHT
            cout << "4What" << endl;
            break;
        }
        case 113:{ //"q"
            return false; //Quit game
        }
        default:{
            cout << "Default..." << endl;
        }
    }
} while(userInput != 5);

嗯,我想你已经忘记如何接收扩展密钥了。

扩展键时自带0xe0,功能键(F1-F12)时自带0x00

改变它
userInput = getch();

userInput = getch();
if (userInput == 0xe0) // for extended keys
{
    userInput = getch();
}
else if (userInput == 0x00) // for function keys
{
    userInput = getch();
}

由于这是Windows,您可以使用ReadConsoleInput读取关键事件。我已经把这些部分分成了函数,但是我真的不认为handleInput的返回语义有那么好。

#include <iostream>
#include <stdexcept>
#include <windows.h>
HANDLE getStdinHandle() {
    HANDLE hIn;
    if ((hIn = GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE) {
        throw std::runtime_error("Failed to get standard input handle.");
    }
    return hIn;
}
WORD readVkCode(HANDLE hIn) {
    INPUT_RECORD rec;
    DWORD numRead;
    while (ReadConsoleInput(hIn, &rec, 1, &numRead) && numRead == 1) {
        if (rec.EventType == KEY_EVENT && rec.Event.KeyEvent.bKeyDown) {
            return rec.Event.KeyEvent.wVirtualKeyCode;
        }
    }
    throw std::runtime_error("Failed to read input.");
}
bool handleInput(WORD vk) {
    switch (vk) {
        case VK_UP:
            std::cout << "upn";
            break;
        case VK_DOWN:
            std::cout << "downn";
            break;
        case VK_LEFT:
            std::cout << "leftn";
            break;
        case VK_RIGHT:
            std::cout << "rightn";
            break;
        case 'Q': //it's Windows; ASCII is safe
            return true;
    }
    return false;
}
int main() {
    try {
        auto hIn = getStdinHandle();
        while (auto vk = readVkCode(hIn)) {
            if (handleInput(vk)) {
                return 0;
            }
        }
    } catch (const std::exception &ex) {
        std::cerr << ex.what();
        return 1;
    }
}

其他有用链接:

  • GetStdHandle
  • INPUT_RECORD
  • KEY_EVENT
  • 虚拟密钥码