[英]nested if/else inside Switch Statement
我试图在case switch语句中嵌入if / else。 当我输入案例'p'或'P'时,无论键入什么字符,都会打印$ 15.00行。 我尝试移动/添加{},但输出没有变化。
感谢您花时间帮助一个菜鸟。
整个代码现在在这里。
#include <stdio.h>
int main()
{
//variable declarations
char typeOfWash, tireShine;
//Menu
printf("R ---> Regular ($5.00)\n");
printf("B ---> Bronze ($7.50)\n");
printf("G ---> Gold ($10.25)\n");
printf("P ---> Platinum ($15.00)\n");
printf("Tire Shine can be added to the Gold or Platinum ONLY,");
printf("for an additional$2.50\n\n");
printf("Enter your selection: ");
scanf("%c",&typeOfWash);
switch (typeOfWash)
{
case 'R': case 'r':
printf("Your bill total is: $5.00\n");
break;
case 'B': case 'b':
printf("Your bill total is: $7.50\n");
break;
case 'G': case 'g':
printf("Would you Like a Tire Shine? (Y/N): ");
scanf("%c ",&tireShine);
if (tireShine == 'Y' || tireShine == 'y')
printf("Your bill total is: $12.75\n");
else
printf("Your bill total is: $10.25\n");
break;
case 'P': case 'p':
printf("Would you Like a Tire Shine? (Y/N): ");
scanf("%c ",&tireShine);
printf("%c",tireShine);
if (tireShine == 'Y' || tireShine == 'y')
printf("Your bill total is: $17.50\n");
else
printf("Your bill total is: $15.00\n");
break;
default:
printf("Invalid Choice");
}
return 0;
}
问题是使用带有%c
格式说明符的scanf
导致空白空间不被消耗,在您的情况下会导致输入缓冲区中的\\n
。 您的教练似乎建议使用下一个scanf
从初始输入中获取尾随空格; 但是,我怀疑他们说要插入一个前导空格而不是尾随空格,因为这可以修复你的问题:
scanf(" %c", &tireShine);
或者,您可以在第二个scanf
之前立即使用getchar()
并预先使用新行字符:
getchar();
scanf("%c", &tireShine);
第二种方法是使用%s
格式说明符而不是%c
并相应地处理它。
请注意, getchar()
只会从输入缓冲区中消耗一个字符。 例如,如果用户要输入长度超过1个字符的字符串,则需要像while ((x = getchar()) != '\\n') ;
清除缓冲区。
尝试内联如果。
case 'P': case 'p':
printf("Would you Like a Tire Shine? (Y/N): ");
scanf("%c",&tireShine);
printf("Your bill total is: $%s\n", toUpper(tireShine) == 'Y' ? "17.50":"15.00");
break;
你还有一个空间。
更改
scanf("%c ", &tireShine);
至
scanf("%c", &tireShine);
尝试这个::
printf("Enter your selection: ");
scanf("%c",&typeOfWash);
fflush(stdin) ;
但要避免使用它。 更新 ::
printf("Enter your selection: ");
scanf("%c",&typeOfWash);
getchar() ;
因为, fflush(stdin)将导致UNDEFINED BEHAVIOR ,您可以使用getchar()来清除流。
scanf()的一个问题是它通常会使“返回”未读。 因此,如果您输入类似'p'的内容然后输入'return',它会读取并处理'p'而不是'return'。 第二次调用scanf()读取已经存在的'return'字符,因此它与'y'或'Y'不匹配。 你对案例'g'有同样的问题。 使用“%c”或“%c”无关紧要。 在具有两个字符来标记行尾的DOS系统上,这个问题可能更糟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.