gpt4 book ai didi

C - Switch-case 打印 case 两次

转载 作者:行者123 更新时间:2023-12-04 10:06:34 24 4
gpt4 key购买 nike

我写了下面的 switch-case:

    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)

为什么它会打印两次问题?谁能帮忙?除此之外,案例按预期运行。

最佳答案

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;

关于C - Switch-case 打印 case 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61558790/

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