我试图在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;
}发布于 2012-09-26 16:56:19
问题是,使用带有%c格式说明符的scanf会导致空白空间不会被使用,在本例中,这会导致在输入缓冲区中留下一个\n。你的讲师似乎建议在下一个scanf中去掉初始输入中的尾随空格;然而,我怀疑他们说插入前导空格而不是尾随空格,因为这解决了您的问题:
scanf(" %c", &tireShine);或者,您可以在第二个scanf之前立即使用getchar(),并预先使用换行符:
getchar();
scanf("%c", &tireShine);第二种选择是使用%s格式说明符代替%c,并相应地处理它。
需要注意的是,getchar()将只使用输入缓冲区中的一个字符。例如,如果用户要输入一个长度超过1个字符的字符串,则需要使用类似于while ((x = getchar()) != '\n') ;的内容来清除缓冲区。
发布于 2012-09-26 15:58:44
尝试内联if。
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;发布于 2012-09-26 15:59:50
你还有一个空间。
变化
scanf("%c ", &tireShine);至
scanf("%c", &tireShine);https://stackoverflow.com/questions/12596994
复制相似问题