代码运行,但表示无效

时间:2015-07-10 17:00:56

标签: c invalidation

当我运行程序时,它会要求输入命令,当您输入a,b或c时,它会提示您根据您选择的值给出该字母。列出的任何其他命令显示统计信我的小问题是当我输入一个有效的命令时,弹出“无效命令”警告,即使它有效

#include <stdio.h>

int main(void)
{
   double a = 0;
   double b = 0;
   double c = 0;
   double d = 0;
   double e = 0;
   double f = 0;
   double g = 0;
   double h = 0;
   double i = 0;

   char command = '\0';

   printf("\n      Welcome\n");
   printf("     Aquapodz Stress Analysis Program\n");
   printf("    ==================================\n");
   while (command != 'x');
   {
      printf("\n\n(a), (b), or (c), enter trial data for        vendor.\n(f)ail-rate,     (m)ean stress, (s)ummary, e(x)it\n");
      printf("Please enter a command");
      scanf("%c", &command);

      if (command == 'a')
      {
         printf("Please enter stress values (GPa) for this trial.");
         scanf("%lf", &a);
         scanf("%lf", &b);
         scanf("%lf", &c);
      }
      else if (command == 'b')
      {
         printf("Please enter stress values (GPa) for this trial.");
         scanf("%lf", &d);
         scanf("%lf", &e);
         scanf("%lf", &f);
      }
      else if (command == 'c')
      {
         printf("Please enter stress values (GPa) for this trial.");
         scanf("%lf", &g);
         scanf("%lf", &h);
         scanf("%lf", &i);
      }
      else if (command == 'f')
      {

         printf("Average failure rate:\nAzuview:%f\nBublon:%f    \nCryztal:%f\n",        a+b+c, d+e+f, g+h+i);
      }
      else if (command == 'm')
      {
         printf("Average mean stress:\nAzuview:%f\nBublon:%f\nCryztal:%f\n",         a+b+c/3, d+e+f/3, g+h+i/3);
      }
      else if (command == 's')
      {
         print("Total (pass / fail) so far:\nAzuview:%f(%f/0)\nBublon:%f(%f/0)        \nCryztal:%f(%f/0)\n", a+b+c, a+b+c, d+e+f, d+e+f, g+h+i, g+h+i);
      }
      else if (command == 'x')
      {

      }
      else
      {
         printf("Invalid Command! Please Try Again :)");
      }

   }
   printf("Goodbye, Please Come Again!");
   return 0;
}

2 个答案:

答案 0 :(得分:1)

  scanf("%c", &command);

是问题所在。您最终会读取上次调用scanf时留下的换行符。使用

  scanf(" %c", &command);

答案 1 :(得分:1)

当您输入任何值时,还会有一个换行符,当您按回车键时它会被输入。由于scanf个模式都不匹配\n,因此它会保留在缓冲区中并在下一个scanf

中被提取

所以不要这样:

scanf("%c", &command);

这样做:

scanf("%c\n", &command);

对于您使用scanf的其他任何地方也一样。