这是我的代码。为什么在我按下右键(向上箭头或向下箭头)时达到默认情况。例如,当我运行它并按 Arrow Up 时,它会达到默认情况,然后如果我再次按下该键,就会达到正确的情况并工作。为什么会这样?
#include <conio.h>
#include <iostream>
#include <windows.h>
using namespace std;
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
#define KEY_RETURN 13
void admin_login()
{
system("cls");
std::string username, password;
/*gotoxy(console::width/2-10,console::height/2-3);*/
std::cout << "\nUsername: ";
std::cin >> username;
std::cout << "\nPassword: ";
std::cin >> password;
}
int main()
{
int c = 0;
int line = 0;
std::string menu_line[] = { "Admin login", "Guest login", "Change color theme", "Exit" };
while(1)
{
system("cls");
for(int i = 0 ; i < 4 ; i++)
{
if(i == line)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),12);
else
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),15);
std::cout << menu_line[i] << '\n';
}
switch((c=getch()))
{
case KEY_UP:
--line;
if(line == -1)
line = 3;
break;
case KEY_DOWN:
++line;
if(line == 4)
line = 0;
break;
case KEY_RETURN:
switch(line)
{
case 0:
system("cls");
admin_login();
break;
}
break;
default:
cout << endl << "null" << endl; // not arrow
system("pause");
break;
}
}
return 0;
}
最佳答案
#define KEY_UP 72
switch((c=getch()))
{
case KEY_UP:
72 是大写 H 字符的 ASCII。
按键盘上的向上光标键键入字母 H 的可能性很小。
实际的解释是,光标移动按键会生成一个多字符代码,很可能是 Esc 代码后跟一两个字符,最后一个是 H.
例如,在我的终端上,向上光标会生成 ESC [ A 字符序列。
您的 for
循环一次读取一个字符。因此,很自然地,当它读取 Esc 时,这将由 default
代码路径处理。并且,在下一次读取(或下一次读取)时,H
被读取,这就是您看到的结果。
关于c++ - 这个开关发生了什么? (C++ 滚动菜单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41450820/