【问题标题】:the program skips all the cases in the switch case and goes to the default程序跳过 switch case 中的所有 case 并转到默认值
【发布时间】:2016-02-26 16:50:58
【问题描述】:

我正在尝试构建一个使用用户输入的小程序,然后使用 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”,它也会进入默认值,而不是适当的大小写。 感谢您的帮助。

【问题讨论】:

  • 您是否尝试过使用调试器?用一个来解决诸如此类的问题是微不足道的。
  • 在这里可以正常工作。你确定你输入的是A 而不是'A'a
  • 请注意,这似乎是特定于 MS 特定的 scanf_s() 函数。使用 scanf() 有效(使用 VS 12 检查)。但是,您应该 avoid using the scanf() family at all and use something like fgets() instead - 阅读整行并解析/处理应用程序中的输入。
  • 您必须阅读手册页:"与 scanf 和 wscanf 不同,scanf_s 和 wscanf_s 需要为 c、C、s、S 等类型的所有输入参数指定缓冲区大小。 .." 所以你缺少一个参数scanf_s("%c",&amp;fuel); 应该是scanf_s("%c",&amp;fuel, 1);
  • @GabrielMichaeli 我们可以看到,您被要求查看似乎行为不端的变量的 实际 值,因为它显然不是您的 认为应该是。

标签: c switch-statement


【解决方案1】:

您没有正确使用scanf_s 函数。根据其documentation

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

并且检查错误也应该完成,所以你应该这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多