c语言如何在switch语句中使用字符串? [英] how use string in switch statement in c programming?
本文介绍了c语言如何在switch语句中使用字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试编译此代码时,我的编译显示错误提示
when i tried to compile this code my compile shows an error saying
"错误:案例标签没有减少到一个整数常量"
" 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 语句中使用的标签必须是整数常量表达式,但如果所有函数具有相同的原型您可以使用字符串和函数的并行数组:
You can not because (as pointed out by @SouravGosh) the labels used in case statement must be an integer constant expression, but if all functions have the same prototype you can use a parallel array of strings and functions:
#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语言如何在switch语句中使用字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文