目前,我正在用c语言做一个项目,在这个项目中,我必须编写一个while循环来不断地接收键盘输入或操纵杆输入。操纵杆输入可以,但键盘输入有两种类型:箭头和普通输入('a','b',.)。对于键盘输入,我参考了这个链接(https://stackoverflow.com/a/11432632)来接收箭头键。这是我的代码:
while(true){
if (getchar() == '\033') { // if the first value is esc
getchar(); // skip the [
switch(getchar()) { // the real value
case 'A':
printf("arrow up \n");
break;
case 'B':
printf("arrow down \n");
break;
case 'C':
printf("arrow right \n");
break;
case 'D':
printf("arrow left \n");
break;
}
}
if (getchar() != '\033'){
printf("non arrow \n");
}
}
然而,“非箭头”经常出现,即使我按箭头按钮。
如果我将printf("non箭头\n")中的代码更改为拥有一个变量char c,将getchar()赋值给它,然后打印c:
if (getchar() != '\033'){
printf("non arrow \n");
}
对于箭头键(接收和按预期打印),输出将与预期的一样,但是当输入'e‘或'r’或其他单个字符键时,什么都不会出现。
我想知道我的代码有什么问题,我如何修改它以接收我想要的行为。
我希望能尽快得到答复。
谢谢你,惠恩。
发布于 2022-04-29 13:58:40
在执行if (getchar() != '\033')
时,您正在读取另一个字符,而不是测试第一次测试的相同字符。
使用else
而不是再次调用getchar()
。
while(true){
if (getchar() == '\e') { // if the first value is esc
getchar(); // skip the [
switch(getchar()) { // the real value
case 'A':
printf("arrow up \n");
break;
case 'B':
printf("arrow down \n");
break;
case 'C':
printf("arrow right \n");
break;
case 'D':
printf("arrow left \n");
break;
default:
printf("non arrow\n");
}
} else {
printf("non arrow \n");
}
}
我在default:
中添加了一个switch
案例,以防他们发送不同的转义序列。您可能还应该检查ESC
之后的第一个字符是[
,而不仅仅是假设它是。
如果有两个以上的条件,可以在那里使用switch(getchar())
,就像在ESC [
之后使用字符一样,或者可以将getchar()
的结果赋值给变量并在条件中进行测试。
此外,在测试相互排斥的条件时,应该使用else if
。
https://stackoverflow.com/questions/72063975
复制