以某些回应打破案例

时间:2015-10-27 08:38:18

标签: c switch-statement break

我正在创建一个得分程序,我遇到了这个案例的问题。当我输入'e'时,它会在默认情况下正确地中断,但它会在第一个switch语句中运行,然后退出程序..

只有当我输入字母'e'时才会发生这种情况。如果我输入'q'或其他任何东西,它就不会退出?

case 'd': // Field Competition Logs
{
  int fieldRound;

  int ifaaField[2], ifaaFieldTotal;
  int ifaaHunter[2], ifaaHunterTotal;
  int fitaField[1];
  int field3D[1];

  printf ("Please select the type of round you shot\n\n");
  printf ("\t(a) IFAA Field\n\t(b) IFAA Hunter\n\t(c) Fita Field\n\t(d) 3D Field\n> ");
  scanf (" %d", &fieldRound);

  switch (fieldRound)
  {
    case 'a': // Ifaa Field Round
    {
      printf ("Please enter the score for your first round > ");
      scanf (" %d", &ifaaField[0]);

      printf ("Please enter the score for your second round > ");
      scanf (" %d", &ifaaField[1]);

      ifaaFieldTotal = ifaaField[0] + ifaaField[1];

      printf ("Total of your first half (%d) and your second half (%d) is %d", ifaaField[0], ifaaField[1], ifaaFieldTotal);

      break;
    }

    case 'b': // Ifaa Hunter Round
    {
      printf ("Please enter the score for your first round > ");
      scanf (" %d", &ifaaHunter[0]);

      printf ("Please enter the score for your second round > ");
      scanf (" %d", &ifaaHunter[1]);

      ifaaHunterTotal = ifaaHunter[0] + ifaaHunter[1];

      printf ("Total of your first half (%d) and your second half (%d) is %d", ifaaHunter[0], ifaaHunter[1], ifaaHunterTotal);

      break;
    }

    case 'c': // Fita Field Round
    {
      printf ("Please enter your Fita Field score > ");
      scanf (" %d", &fitaField[0]);

      printf ("Total of your Fita Field round is %d", fitaField[0]);

      break;
    }

    case 'd': // Field 3D Round
    {
      printf ("Please enter your 3D Field score > ");
      scanf (" %d", &field3D[0]);

      printf ("Total of your 3D Field round is %d", field3D[0]);

      break;
    }

    default:
    printf ("Please enter a valid response");
    break;
  }

  break; // Breaks out of Case D

}

case 'e': // Exits the program
{
  printf ("Thank you, Good bye!\n");
  return 0;
}

输出

Please select the type of round you shot

    (a) IFAA Field
    (b) IFAA Hunter
    (c) Fita Field
    (d) 3D Field
> e
Please enter a valid response
Hi s. c, Please choose from the following options by typing the letter and pressing the 'return' key

    (a) Enter Scored Practice logs
    (b) Enter Practice Arrow count
    (c) Enter Competition logs
    (d) Enter Field Competition Logs
    (e) Exit Program
> Thank you, Good bye!

2 个答案:

答案 0 :(得分:1)

        scanf (" %d", &fieldRound);

scanf失败了!它期望数字输入,而不是字母字符!

答案 1 :(得分:1)

更改

        scanf (" %d", &fieldRound);

        scanf (" %c", &fieldRound);

在当前配置中,scanf需要十进制数字,而不是字符。如果你尝试输入一个角色,它就会失败。

此外,您需要将int fieldRound;更改为char fieldRound;