gpt4 book ai didi

c++ - getch 结合 while-loop 两次触发 loopcontent

转载 作者:行者123 更新时间:2023-11-28 04:45:05 35 4
gpt4 key购买 nike

我不是真正的程序员,所以我的知识非常有限,我只是希望得到一个非常基本的程序来为一个项目工作。我一直在谷歌上搜索很多,从我发现的情况来看,我猜它与 getch 读取空格或换行作为输入或类似的东西有关。然而,我发现的所有解决方案似乎都无法为我解决问题(尽管我可能实现错误)。

这是在主函数中:

while (roundNum <= 20)
{

roundNum++;

cout << roundNum / 2 << endl;
arrowKey();


}

arrowKey 函数(我通过谷歌搜索找到的,所以我没有)看起来像这样:

int arrowKey()
{
int c = 0;
switch ((c = _getch()))
{
case KEY_UP:
cout << endl << "Up" << endl;
break;
case KEY_LEFT:
cout << endl << "Left" << endl;
break;
case KEY_RIGHT:
cout << endl << "Right" << endl;
break;
case KEY_DOWN:
cout << endl << "Down" << endl;
break;
}
return 0;
}

问题是 roundNum 读出两次并在每次按下箭头键时将数字加 2,如下所示:

 1
1

Up
2
2

Right
3
3

等等

非常感谢您的帮助!

最佳答案

问题是 char 只能保存 255 个值。因此,为了得到更多的唯一值,getch有时会使用两个值来表示一个键码,一个指令和一个值。例如,尝试按下 F 键,您会发现同样的问题出现了。

最终,您遇到的行为是由于为方向键调用了两次 getch

要解决此问题,请检查指令是否针对箭头键,在本例中,箭头键的值为 224。确定按下箭头键后,通过再次调用 getch 读取第二个值,然后您将能够找到实际的键。

#include <iostream>
#include <conio.h>
using namespace std;
enum KeyCodes {
KEY_UP = 72,
KEY_LEFT = 75,
KEY_RIGHT = 77,
KEY_DOWN = 80
};
int arrowKey()
{
int c = _getch();
if (c == 224) {
//another value
int key = _getch();

switch (key)
{
case KEY_UP:
cout << endl << "Up" << endl;
break;
case KEY_LEFT:
cout << endl << "Left" << endl;
break;
case KEY_RIGHT:
cout << endl << "Right" << endl;
break;
case KEY_DOWN:
cout << endl << "Down" << endl;
break;
}
}

return 0;
}

int main() {
int roundNum = 0;
while (roundNum <= 20)
{
roundNum++;
cout << roundNum / 2 << endl;
arrowKey();
}
}

还值得指出的是,getch 不是 std 库的一部分,因此可能会有一些变化。

关于c++ - getch 结合 while-loop 两次触发 loopcontent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49410195/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com