我终于抓住了C中的箭头键。我已经找到了如何让C检测它们并实际上已经制作了它的程序。
问题是......该程序被窃听。我不知道我做错了什么。
CODE:
#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”。知道为什么吗?
尝试编译它并继续使用箭头键。走着瞧吧。将不胜感激给予任何帮助!
答案 0 :(得分:1)
执行/ 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';
}
}