【发布时间】:2020-09-01 13:55:11
【问题描述】:
我有一个代码 sn-p,我用它来学习一些 C
char* input( char *s ){
scanf("%[^\n]%*c",s);
return s;
}
void main()
{
printf("Welcome to a string input/output example written in C! \n");
printf("Type e to exit \n");
printf(" \n");
while (0 == 0){
printf("> ");
char str[100];
input( str );
//All off this code works perfectly until the switch statement, which apparently cannot recognized the 'e' case:
switch(str){
case 'e' : break;
default : printf("Your string is: %s \n", str);
}
}
}
然而,当这段代码运行时,它返回的字符串很好,但是在 switch 语句期间它默认为默认值,即使“str”的值为“e”,它也会返回:
你的字符串是:e
而不是退出。请帮忙,这很奇怪..
【问题讨论】:
-
while (0 == 0)是无意义的代码。只需使用while (1)或for (;;)。 -
提示:你不能在 C 字符串上使用
switch。使用strcmp。 -
switch在 C 中仅用于整数分支。 -
另外,
switch内的break不会脱离while循环。
标签: c string switch-statement c-strings