如何在c编程中使用switch语句中的字符串?

时间:2016-04-18 07:35:46

标签: c string switch-statement

当我尝试编译此代码时,我的编译显示错误

  

"错误:案例标签不会减少为整数常量"

请告诉我我在做错的地方。

void main()
{
    int i,a,b;
    char c[10];

    printf("\n Input length  of sides in (a,b) format \n");
    scanf("(%d,%d)",&a,&b);

    printf("\n calculate -");

    while(c[10]!="Area\0" || "Perimeter\0")
    {
        scanf("%s",c[10]);  
    }

    switch(c[10])
    {
        case "Area":
            area(a,b);
            break;          
        case "Perimeter":
            perimeter(a,b);
            break;
    }
}

4 个答案:

答案 0 :(得分:3)

你不能因为(正如@SouravGosh所指出的)case语句中使用的标签必须是一个整型常量表达式,但如果所有函数都有相同的原型,你可以使用字符串和函数的并行数组:

#include <stdio.h>
#include <string.h>

int area(int a, int b)
{
    return printf("Area: %d %d\n", a, b);
}

int perimeter(int a, int b)
{
    return printf("Perimeter: %d %d\n", a, b);
}

int main(void)
{
    char buf[256];
    const char *ap[] = {"Area", "Perimeter", NULL}; /* An array of strings */
    int (*fn[])(int, int) = {area, perimeter, NULL}; /* An array of functions */
    const char **pp = ap; /* A pointer to the first element of ap */

    printf("Enter your function name: ");
    scanf ("%s", buf); /* Get users input */
    while (*pp != NULL) {
        if (strcmp(buf, *pp) == 0) { /* Found it */
            fn[pp - ap](1, 2); /* Execute fn() using the same offset of pp */
            break; /* Exit loop */
        }
        pp++; /* Next string */
    }
    return 0;
}

答案 1 :(得分:1)

首先,

scanf("%s",c[10]);

非常错误,你需要写

 scanf("%9s", c);

也就是说,case语句中使用的标签必须是整数类型(整数常量表达式)。您不能将字符串文字用作案例标签,并期望它们执行字符串比较类型操作。

根据C11,第6.8.4.2章

  

每个case标签的表达式应为整数常量表达式,而不是两个   同一case语句中的switch常量表达式应具有相同的值   转换后。 [...]

如果必须使用字符串类型用户输入来确定大小写,最好的方法是

  • 使用fgets()阅读输入。
  • 使用strcmp()检查是否相等。
  • 根据之前的比较结果设置标记。
  • 使用switch和案例陈述中的旗帜值。

答案 2 :(得分:0)

The standard说:

  

6.8.4.2 switch语句

     

约束

     

1 switch语句的控制表达式应具有   整数类型

所以你永远不能在switch语句中使用字符串(即if(value){} // false is value === false or value === 0 static数组)。

答案 3 :(得分:-2)

如果您想在“if / else”

中使用字符串
// switch statement
switch (string) {
  case "C": 
    // code 
    break;
}