[英]C switch not recognising string
I am trying to take a user input in the form of a string and then use that in a switch, but it always ends up using the default case and not the case for the string I inputted. 我试图以字符串形式获取用户输入,然后在开关中使用该输入,但是最终总是使用默认的大小写而不是我输入的字符串的大小写。 For the purpose of testing I am inputting just the letter y into this:
为了进行测试,我仅在其中输入字母y:
char thing[1];
scanf("%s",thing);
switch(thing){
case 'y' :
printf("yup\n");
break;
default :
printf("nope\n");
}
This char array has one element. 此char数组具有一个元素。 Your code is crying for a
char
here. 您的代码在这里
char
。 You will do fine with a char
and then get input and check it. 您可以将一个
char
做的很好,然后获取输入并进行检查。 Also here in switch
you have used an pointer value which didn't match with the char
like y
etc . 这里也是
switch
您使用了指针值不与匹配char
像y
等。 Went to default. 设为默认值。
char thing;
if(scanf("%c",&thing) != 1){
// error
}
..
If you want to use strcmp
beware that you need to have null terminated char array. 如果要使用
strcmp
请注意,您必须具有以null结尾的char数组。
char thing[3];
if(scanf("%2s",thing)!= 1){
// error
}
if(strcmp(thing,"y") == 0){
printf("yup\n");
}
else{
printf("nope\n");
}
Also you could have done this with your code - but that is not helpful given that you can't use it as null terminated char array
or string which many of the standard string processing function demands. 同样,您也可以使用代码来完成此操作-但这对您没有帮助,因为您不能将其用作以
null terminated char array
或许多标准字符串处理功能所需的字符串。
char thing[1];
if(scanf("%c",&thing[0]) != 1){
// error
}
switch(thing[0]){
case 'y' :
printf("yup\n");
break;
default :
printf("nope\n");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.