【问题标题】:Why doesn't this switch case program take character input after the integer input? [duplicate]为什么这个 switch case 程序在整数输入之后不接受字符输入? [复制]
【发布时间】:2017-02-06 14:59:37
【问题描述】:
#include <stdio.h>

int main() {

    char operator;
    int a,b;    

    printf("Enter 1st operands: ");
    scanf("%d",&a);    

    printf("Enter 2nd operands: ");
    scanf("%d",&b);

   //here after taking the input of integers the code skips to default without 
//taking the character input 

    printf("Enter an operator (+, -, *,/): ");
    scanf("%c", &operator);

    switch(operator)
    {
        case '+':
            printf("%d+ %d = %d",a, b, a + b);
            break;

        case '-':
            printf("%d- %d = %d",a, b, a - b);
            break;

        default:
            printf("Error! operator is not correct");
    }

    return 0;
}

【问题讨论】:

  • @xing:请在答案部分写下答案,以便同行评审。
  • 您能详细说明一下吗?或提供任何描述性链接?我没有正确理解这件事。蒂亚

标签: c switch-statement character calculator


【解决方案1】:

scanf("%c", &amp;operator); 实际上读取输入流中保留的换行符。

补救措施 - scanf(" %c", &amp;operator); - 注意空格,是绕过这个的惯用方式。

【讨论】:

  • 您能详细说明一下吗?或提供任何描述性链接?我没有正确理解这件事。蒂亚
  • 拿出你最喜欢的调试器。查看switch 块之前的operator。赌一赌它是 10,对应于您按下键盘上的 Return 键时发生的情况。
【解决方案2】:

scanf(" %c", &operator);
      ^^^^

否则控制字符将存储在对象中。

来自 C 标准中的函数描述(7.21.6.2 fscanf 函数)

5 由空白字符组成的指令由 读取输入直到第一个非空白字符(仍然是 未读),或直到无法读取更多字符。

【讨论】:

  • 您能详细说明一下吗?或提供任何描述性链接?我没有正确理解这件事。蒂亚
  • @AlinoorRahman 查看我更新的帖子。
猜你喜欢
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 2023-01-08
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多