gpt4 book ai didi

c - 在 C 语言中使用方向键

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:12 24 4
gpt4 key购买 nike

我终于掌握了 C 中的箭头键。我发现了如何让 C 检测到它们并实际编写了一个程序。

问题是……程序有问题。我不知道我做错了什么。

代码:

#include <stdio.h>
main()
{
char menitem[3][32], key, key2;
int i = 0;
strcpy(menitem[0], "Option 1 [X]");
strcpy(menitem[1], "Option 2 [ ]");
strcpy(menitem[2], "Option 3 [ ]");
start:
system("cls");
printf("%s\n%s\n%s", menitem[0], menitem[1], menitem[2]);
key = getch();
key2 = 0;
if(key = 0xE0)
key2 = getch();
ret:
if(i == 0)
{
switch(key2)
{
case 80:
strcat(menitem[0], "\b\b ]");
i++;
strcat(menitem[i], "\b\bX]");
goto start;
default: goto ret;
}
}
else if(i == 2)
{
switch(key2)
{
case 72:
strcat(menitem[2], "\b\b ]");
i--;
strcat(menitem[i], "\b\bX]");
goto start;
default: goto ret;
}
}
else
{
switch(key2)
{
case 80:
strcat(menitem[i], "\b\b ]");
i++;
strcat(menitem[i], "\b\bX]");
goto start;
case 72:
strcat(menitem[i], "\b\b ]");
i--;
strcat(menitem[i], "\b\bX]");
goto start;
default: goto ret;
}
}
}

问题是:

当我从选项 2 上升时,选项 3 变成“X]”。知道为什么吗?

尝试编译它并继续使用箭头键。走着瞧吧。将不胜感激任何帮助!

最佳答案

执行/b 并删除输入,然后一遍又一遍地添加输入,这不是一个好主意。首先,如果用户按下大量箭头键,您将获得大量退格/删除字符,并且您的字符串会变得非常大。您遇到问题是因为您在某些情况下删除了太多字符。相反,只需对 [] 内的字符进行内存修改。我将使用可行的解决方案编辑这篇文章。

编辑这是一个可行的解决方案:

#include <stdio.h>
int main()
{
char menitem[3][32], key, key2;
int i = 0;
int currentlySelectedItem = 1;
strcpy(menitem[0], "Option 1 [X]");
strcpy(menitem[1], "Option 2 [ ]");
strcpy(menitem[2], "Option 3 [ ]");
while(1)
{
system("cls");
printf("%s\n%s\n%s", menitem[0], menitem[1], menitem[2]);
key = getch();
key2 = 0;
if(key == -32)
{
key2 = getch();
}
else
{
continue;
}
if(key2 == 80)
{
currentlySelectedItem++;
}
else if(key2 == 72)
{
currentlySelectedItem--;
}

//make sure the selected item stays in range
if(currentlySelectedItem < 1)
currentlySelectedItem = 1;
if(currentlySelectedItem > 3)
currentlySelectedItem = 3;

menitem[0][10] = ' ';
menitem[1][10] = ' ';
menitem[2][10] = ' ';
menitem[currentlySelectedItem-1][10] = 'X';

}

}

关于c - 在 C 语言中使用方向键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21325724/

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