C语言 使用 goto 时程序运行方式不同



嗨,我是 C 编程的新手。 我正在尝试创建一个计算器。 我成功地做到了这一点,但是当我尝试让程序重新开始以便用户可以提出另一个问题时,它无法正常工作。 它看起来像这样

Type what operation you want to do(+, -, *, /:)
*
Enter two operands:
 8
8
The product of the two numbers is64
Type what operation you want to do(+, -, *, /:)
Enter two operands:
 gg
Type what operation you want to do(+, -, *, /:)
Enter two operands:
 Type what operation you want to do(+, -, *, /:)
Enter two operands:

它跳过输入的第一行,无论我键入多少个字符,它都会做同样的事情。 这是我的代码

#include <stdio.h>
int main() {
  start:;
  char operator;
  int a, b, sum, differnce, product, quotient;
  printf("Type what operation you want to do(+, -, *, /:)n");
  scanf("%c", &operator);
  printf("Enter two operands:n " );
  scanf("%d%d",&a,&b);
  switch(operator)
  {
    case '+':
      sum = a + b;
      printf("The sum of the two numbers is:%dn",sum);
      break;
    case '-':
      differnce = a - b;
      printf("The differnce of the two numbers is:%dn",differnce);
      break;
    case '*':
      product = a * b;
      printf("The product of the two numbers is%dn",product);
      break;
    case '/':
      quotient = a / b;
      printf("The quotient of the two numbers is %dn", quotient);
      break;
  }
  goto start;
  return 0;
}

现在我知道goto命令不是很好,所以如果有可行的替代方案,我愿意接受它。

读取char后,您应该清理缓冲区。不要使用fflush(stdin)——这是一种不好的做法。您可以改为添加此函数:

void clean_stdin(void)
{
    int c;
    do {
        c = getchar();
    } while (c != 'n' && c != EOF);
}

并在"扫描"之后调用它:

 scanf("%c", &operator);
 clean_stdin();`

关于 GOTO:您可以使用循环 — 可能是while循环,也可能是for循环或do … while循环。 这些比使用goto语句和标签更容易理解。

更新

或者,正如@BLUEPIXIE建议的那样,您可以通过以下方式更改scanf

scanf(" %c", &operator); // adding a space before %c

问题实际上不在于goto语句,而在于scanf("%c",...)将消耗一个新行,该行可能位于先前输入的整数值之后的缓冲区中。

假设以下代码:

int main() {
    char operator;
    int a;
    printf("Enter an integral value:n " );
    scanf("%d",&a);
    printf("Try to enter an operator (will probably be skipped):n " );
    scanf("%c", &operator);
    if (operator == 'n')
        printf("You entered a new line (did you?)n");
    else
        printf("You entered: %cn", operator);
    return 0;
}

如果输入整数值并按 <enter> ,则缓冲区中将保留换行符。这立即被后续的 scanf 语句使用。因此,例如,如果您输入; 19并按 <enter> ,您将获得以下输出:

Enter an integral value: 19
Try to enter an operator (will probably be skipped):
 You entered a new line (did you?)

但是,如果您按照melpomene的建议使用以下语句:

scanf(" %c", &operator);

然后scanf在实际将第一个非空格字符读入%c->&operator之前,将使用任意长序列的空格字符(包括换行符(:

Enter an integral value:
 19
Enter an operator:

+
You entered: +

相关内容

最新更新