简体   繁体   English

如何使switch-case语句不区分大小写?

[英]How can I make switch-case statements case insensitive?

How can I make a switch-case statement to not be case sensitive? 如何使switch-case语句不区分大小写? Say I made something like this: 说我做了这样的事情:

#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;
}
}

It would only respond to capital letters. 它只会回应大写字母。 How do I make it respond to lower case letters? 如何让它回复小写字母?

toupper in <ctype.h> converts a character to uppercase: <ctype.h> toupper将字符转换为大写:

#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;
}

You simply need this :- 你只需要这个: -

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;
}

and so on to continue your series. 等等继续你的系列。

Actually,what it does is that it bypasses(skims) upto bottom until it finds the first break statement matching the case thereby executing all the cases encountered in between!!! 实际上,它做的是它绕过(skims)到底部,直到它找到匹配case的第一个break语句,从而执行中间遇到的所有情况!

Before the switch(), add: 在switch()之前,添加:

choice = toupper(choice);

And if you haven't already got it, #include <ctype.h> to get the prototype. 如果你还没有它, #include <ctype.h>来获取原型。

You can give 2 cases one by one, 你可以逐一给出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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM