c-为什么这个switch/case语句只执行默认的case



当用户输入Yes、Only Maths、Only Science时,编译器执行Default。我尝试过使用相同的代码,但用Int替换Char后,它可以按预期工作。。但有了木炭就没有了。。

#include<stdio.h>
int main(){

char a;
printf("Have you passed in both maths and science?[Yes,Only Maths,Only Science]");
scanf(" %c", &a);
switch (a){
case 'Yes':
printf("That's amezing!");
break;
case 'Only Maths':
printf("That's good!");
break;
case 'Only Science':
printf("That's good!");
break;
case 'none':
printf("oof work harder next time!, i hope you will rock on that exam!");
break;
default:
printf("bozo do the typing right!");
break;
}
return 0;
}

一个字符本身不能存储像"是的";。它将只存储第一个"Y",并保留其余的。这就是为什么没有一个开关案例会匹配。考虑使用字符串或字符数组来存储可以进行比较的字符数组。然而,问题变成了不能在C中使用带字符串的switch,所以必须使用if,else。

#include <stdio.h>
int main(){
char a[15]; //15 should be a reasonable size
printf("Have you passed in both maths and science?[Yes,Only Maths,Only Science]");
fgets(a, 15, stdin);

if (strcmp(a, "Yes") == 0) printf("That's amezing!");
else if (strcmp(a, "Only Maths") == 0) printf("That's good!");
else if (strcmp(a, "Only Science") == 0) printf("That's good!");
else if (strcmp(a, "none") == 0) printf("oof work harder next time!, i hope you will rock on that exam!");
else printf("bozo do the typing right!");

return 0;
}

还建议使用fgets而不是scanf来读取字符串。