为什么switch总是运行default?(与休息;包括)
Why does switch always run default? (with break; included)
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
- 虚拟密钥码
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 为什么 cmake 许可证<>样式不包括?
- 计算平均值,不包括上次得分
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 从多个源构造一个对象,包括一个对象向量
- 通过switch和static_cast访问多态对象的运行时类型
- 如何将 if else 语句重写为 switch 语句
- 在编译中包括 Botan 2
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- 将值从另一个数组写入数组,不包括不需要的值 C++
- VS Code C++:不准确的系统包括路径错误(wchar.h,boost/lambda/lambda.hpp)
- Switch 语句(字符串)一直选择默认值,除非其为零
- 包括C++头文件
- CPP 包括 Azure DevOps 中的目录设置
- 包括STL,而不会乱扔全球范围
- 如何反转我的输入,包括否定
- 包括没有完整路径的我的库
- 如何在 android ndk 上链接 C 和 C++ 代码,以及 C 和 C++ 运行时库(包括 STL)?
- 为什么switch总是运行default?(与休息;包括)