【发布时间】:2018-09-20 15:06:30
【问题描述】:
我正在处理一项允许用户输入“类型”和“重量”的任务,它会显示成本。这是代码。我希望它一直运行直到用户输入“n”。
main()
{
char type,chr;
float cost,weight;
do
{
printf("Insert the type of fish: "); /*inputs type and weight*/
scanf("%c",&type);
printf("insert weight: ");
scanf("%f",&weight);
switch(type)
{
case 'K':
case 'k':
cost=weight*9.00;
break;
case 'R':
case 'r':
cost=weight*10.00;
break;
case 'S':
case 's':
cost=weight*12.00;
break;
case 'G':
case 'g':
cost=weight*8.00;
break;
case 'T':
case 't':
cost=weight*15.00;
break;
default :
printf("Invalid type\n");
}
printf("The cost of fish is:%.2f \n",cost);
printf("Do you want to continue?Y/N: ");
scanf(" %c",&chr);
}
while(chr == 'Y' || chr == 'y');
}
我使用了do..while 循环,它工作正常,直到我输入“y”并且我无法输入类型。
【问题讨论】:
-
嗨!欢迎来到 StackOverflow!我建议您通过以下方式提高问题的质量:使用正确的格式/缩进将标题保持在最低限度。另请参阅How do I ask a good question?。
-
使用
fgets()(可能后跟sscanf())进行用户输入。scanf()在错误处理/恢复方面相当糟糕,而且管理空白也很尴尬。您的直接问题是在 scanf(" %c", &chr);之后仍在输入缓冲区中。 -
我认为这是 scanf 被跳过的问题。请看这个答案。 stackoverflow.com/a/29775377/5774004
-
@SreeraghAR 我认为这似乎是问题所在,我所要做的就是在“%c”中添加空间。非常感谢!!!!