【问题标题】:how use string in switch statement in c programming? [closed]如何在c编程中的switch语句中使用字符串? [关闭]
【发布时间】:2016-04-18 07:35:45
【问题描述】:

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

" 错误:case 标签没有减少为整数常量"

请告诉我我在哪里做错了。

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

【问题讨论】:

  • 你必须使用strcmp来比较字符串。
  • 先学习数组和指针。然后学习弦乐。在你尝试编写这个程序之前,你必须知道这些事情,你不能只是“猜测”如何编写它。首先,您必须意识到 C 没有像其他编程语言那样内置的、预制的字符串类。
  • 这段代码表明对这么多基础知识缺乏理解,我投票结束这个问题“过于宽泛”。

标签: c string switch-statement


【解决方案1】:

你不能因为(正如@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;
}

【讨论】:

  • 代码不错,但是 OP 以他c 的知识水平怎么能看懂呢?...
  • @LPs,好点,我会尽力解释...
【解决方案2】:

首先,

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

非常错误,你需要写

 scanf("%9s", c);

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

根据C11,第 6.8.4.2 章

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

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

  • 使用fgets()读取输入。
  • 使用strcmp() 来检查是否相等。
  • 根据之前的比较结果设置一个标志。
  • 在switch 和case 语句中使用标志值。

【讨论】:

  • 很想听听 DV 背后的原因...
【解决方案3】:

The standard 说:

6.8.4.2 switch 语句

约束

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

因此,您永远不能在 switch 语句中使用字符串(即const char 的static 数组)。

【讨论】:

  • 有人可能想补充一点,实际上C中没有数据类型“字符串”。
  • @alk 是的,答案改进了
【解决方案4】:

如果你想像“if/else”那样使用字符串

// switch statement
switch (string) {
  case "C": 
    // code 
    break;
}

【讨论】:

  • 这是完全错误的,抱歉。
猜你喜欢
  • 2021-06-07
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多