c - C - Switch-case 打印 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;
推荐阅读
- performance - Julia:有效地将压缩元组映射到元组
- c - 为什么 GCC atomic builtins 需要一个额外的“通用”版本?
- python - 将时间字符串格式化为 100 毫秒 - Python
- python - 跨kd树的双重递归以找到两组点之间的最接近方法
- reactjs - 检测 React 中的 URL 参数变化
- typescript - 在 three.js 中使用带透明的 RawShaderMaterial 操作 InstancedBufferGeometry 深度缓冲区的正确方法?
- java - 来自 RGB byte[] 数组的 BufferedImage
- r - R:在 Shiny 中使用公式对象来检索描述性统计数据
- javascript - 嵌套的 .then 的 JS 返回值
- c - 与哨点值相反