为什么这个开关案例程序在整数输入后不接受字符输入?

时间:2017-02-06 14:59:37

标签: c switch-statement character calculator

#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;
}

2 个答案:

答案 0 :(得分:2)

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

补救措施 - scanf(" %c", &operator); - 注意空间,是解决这个问题的惯用方法。

答案 1 :(得分:1)

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

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

来自C标准中的功能描述(7.21.6.2 fscanf功能)

  

5由白色空格字符组成的指令由。执行   读取输入到第一个非白色空间字符(仍然存在   未读),或直到不再能读取任何字符。