如何使switch-case语句不区分大小写? 说我做了这样的事情:
#include <stdio.h>
char choice;
int main ()
{
char choice;
printf("Will you choose A,B, or C?\n>");
scanf(" %c", &choice);
switch(choice)
{
case 'A':
printf("The First Letter of the Alphabet");
break;
case 'B':
printf("The Second Letter of the Alphabet");
break;
case 'C':
printf("The Third Letter of the Alphabet");
break;
}
}
它只会回应大写字母。如何让它回复小写字母?
答案 0 :(得分:30)
toupper
中的 <ctype.h>
将字符转换为大写:
#include <stdio.h>
#include <ctype.h>
char choice;
int main ()
{
printf("Will you choose A,B, or C?\n>");
scanf(" %c", &choice);
switch(toupper(choice)) // Changed line
{
case 'A':
printf("The First Letter of the Alphabet");
break;
case 'B':
printf("The Second Letter of the Alphabet");
break;
case 'C':
printf("The Third Letter of the Alphabet");
break;
}
答案 1 :(得分:14)
你只需要: -
switch(choice)
{
case 'A':
case 'a':
printf("The First Letter of the Alphabet");
break;
case 'B':
case 'b':
printf("The Second Letter of the Alphabet");
break;
case 'C':
case 'c':
printf("The Third Letter of the Alphabet");
break;
}
等继续你的系列。
实际上,它的作用是它绕过(skims)到底部,直到它找到匹配大小写的第一个break语句,从而执行中间遇到的所有情况!!!
答案 2 :(得分:6)
在切换()之前,添加:
choice = toupper(choice);
如果你还没有得到它,#include <ctype.h>
来获得原型。
答案 3 :(得分:1)
您可以逐个提供2个案例,
switch(choice)
{
case 'A':
case 'a':
printf("The First Letter of the Alphabet");
break;
case 'B':
case 'b':
printf("The Second Letter of the Alphabet");
break;
case 'C':
case 'c':
printf("The Third Letter of the Alphabet");
break;
}