我写了下面的开关案例。
char input;
int run = 1;
while(run){
printf("Would you like to update the student's name? Enter Y or N (Y=yes, N=no)\n");
input = getchar();
switch (input)
{
case 'N':
run = 0;
break;
case 'n':
run = 0;
break;
case 'Y':
printf("Please enter the updated name\n");
scanf("%s", st->name);
run = 0;
break;
case 'y':
printf("Please enter the updated name\n");
scanf("%s", st->name);
run = 0;
break;
case '\n':
break;
default:
printf("Wrong input. Please enter a valid input (Y or N)\n");
}
}
当我运行时,它是这样的:
Please enter the id of the student that you would like to update
1
Would you like to update the student's name? Enter Y or N (Y=yes, N=no)
Would you like to update the student's name? Enter Y or N (Y=yes, N=no)
为什么会打印两次问题?有谁能帮助我吗?除此之外,case的运行符合预期。
函数 getchar
读取所有字符,包括新行字符。而使用
scanf( " %c", &input );
另外你的switch语句有重复的代码。比如说,你可以写
switch (input)
{
case 'N':
case 'n':
run = 0;
break;
case 'Y':
case 'y':
printf("Please enter the updated name\n");
scanf("%s", st->name);
run = 0;
break;
//...
同样的方法你也可以用在switch语句的其他标签上,并删除这段代码。
case '\n':
break;