【发布时间】:2021-11-08 13:30:00
【问题描述】:
我对编程很陌生,我知道 scanf() 有一些怪癖。也就是说,当它检测到与其转换说明符不匹配的字符时,它会立即返回并将有问题的字符放回缓冲区,以便由另一个 scanf() 调用或其他可以访问缓冲区的函数读取. 但是,我正在做书本练习,代码行为很奇怪。
float total = 0, operand = 0;
char operator = 0;
printf("Enter an expression: ");
scanf("%f ", &total);
while ((operator = getchar()) != '\n') {
scanf("%f", &operand);
switch (operator) {
case '+':
total += operand;
break;
case '-':
total -= operand;
break;
case '*':
total *= operand;
break;
case '/':
total /= operand;
break;
}
printf("Value of operator: %c\n", operator);
printf("Operand: %f\n", operand);
}
printf("Value of expression: %f\n", total);
两个 printf 调用用于测试。输入:“1 + 5 + 9\n”导致:
Value of operator: +
Operand: 5.000000
Value of operator:
Operand: 5.000000
Value of operator:
Operand: 9.000000
Value of expression: 6.000000
所以,程序似乎是这样的: scanf() 将 1 读入 'total',将其后面的空格与格式字符串中的空格配对,遇到 '+',然后将其放回缓冲区并返回。
然后:
循环 1 - getchar() 读取剩余的 '+' 并将其放入 'operator'。 scanf() 读取 5,遇到空格,放回缓冲区,然后返回。
循环 2 - getchar() 读取剩余的 ' ',并将其放入 'operator' scanf() 遇到 '+' 并立即返回并将其放回缓冲区。
这就是我的理解不一致的地方。在循环 3 开始时,getchar() 应该遇到 '+' 并将其存储到 'operator' 中。相反,它被完全跳过了,对我来说毫无意义。
【问题讨论】:
-
尝试逐句调试,看看发生了什么。
-
总是检查函数调用的返回值,特别是库的返回值。