gpt4 book ai didi

c - C语言中switch语句中如何使用字符串?

转载 作者:行者123 更新时间:2023-11-30 21:20:34 25 4
gpt4 key购买 nike

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

" error: case label does not reduce to an integer constant"

请告诉我我哪里做错了。

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

最佳答案

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

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

关于c - C语言中switch语句中如何使用字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36687935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com