程序跳过开关盒中的所有情况并转到默认值

时间:2015-11-24 09:54:27

标签: c switch-statement

我正在尝试构建一个使用用户输入的小程序,然后使用switch case执行适合用户输入的操作。 我一直在努力找到我的计划中的错误,没有运气。显然我缺少一些东西。

这是代码,你能帮我找到它的错误吗?

#include <stdio.h>
#define A 8.5
#define B 7.6
#define C 7.7
#define D 7.7

int main ()
{


    char fuel;
    float amount,total;

    printf("please enter the desired fuel\n");
    scanf_s("%c",&fuel);

   switch(fuel)
   {
   case 'A' :
         printf("how many liters of fuel do you want?\n");
         scanf_s("%f",&amount);
         total=amount*A;
         if(total>150)
         {
             printf("the total price to pay is %.3f: \nYou have won a newspaper", total);
         }
         else
         printf("the total price to pay is %.3f", total);
         break;

      case 'B' :
          printf("how many liters of fuel do you want?\n");
         scanf_s("%f",&amount);
         total=amount*B;
         if(total>150)
             printf("the total price to pay is %f: \nYou have won a newspaper", total);
         else
         printf("the total price to pay is %.3f", total);

          break;
      case 'C' :
         printf("how many liters of fuel do you want?\n");
         scanf_s("%f",&amount);
         total=amount*C;
         if(total>150)
             printf("the total price to pay is %f: \nYou have won a newspaper", total);
         else
         printf("the total price to pay is %.3f", total);
         break;

      case 'D' :
         printf("how many liters of fuel do you want?\n");
         scanf_s("%f",&amount);
         total=amount*D;
         if(total>150)
             printf("the total price to pay is %f: \nYou have won a newspaper", total);
         else
         printf("the total price to pay is %f", total);

      break;

      default: 
      printf("no\n");
      break;
   }



}

即使我输入'A','B','C'或'D',它也会变为默认值,而不是适当的情况。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:5)

您没有正确使用scanf_s功能。根据其documentation

  

与scanf和wscanf不同,scanf_s和wscanf_s需要缓冲区大小   要为c,C,s,S或string类型的所有输入参数指定   包含在[]中的控件集。缓冲区大小以字符为单位   在指针指向后立即作为附加参数传递   缓冲区或变量。

还应该检查错误,所以你应该这样做:

char fuel;
if (scanf_s("%c", &fuel, 1) != 1)  {
    puts("Error from scanf_s");
    return 1;
}