[英]Using Arrow Keys in C
我终于掌握了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';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.