在此C程序中,第二个scanf被跳过,如果我使用fflush则工作正常。为什么会这样呢?

时间:2019-03-09 04:57:44

标签: c scanf

在此C程序中,如果我在第二个fflush(stdin)之前使用scanf,则可以正常工作。并在操作数之前扫描运算符,然后它开始工作。我不明白,为什么它会那样工作。

#include<stdio.h>
int main() {
    int a,b,c;
    char d;
    printf("Enter  two operands:");
    scanf("%d%d",&a,&b);
    printf("\nEnter the operation you desire to perform on Calculator and i.e +, -, *, /  :\n");
    fflush(stdin);
    scanf("%c",&d);

    switch(d) {
        case '+': printf("\n%d %c %d =%d",a,d,b,(a+b));
            break;
        case '-': printf("\n%d %c %d =%d",a,d,b,(a-b));
            break;
        case '*': printf("\n%d %c %d =%d",a,d,b,(a*b));
            break;
        case '/': (a>b)?(printf("\n%d %c %d =%d",a,d,b,(a/b))):(printf("\n%d %c %d =%d",a,d,b,(b/a)));
            break;
        default: printf("\nInvalid input");
    }
    return 0;
}

输出:

enter image description here

1 个答案:

答案 0 :(得分:0)

只需将您的代码修改为此:

#include<stdio.h>
int main() {
    int a,b,c;
    char d;
    printf("Enter  two operands:");
    scanf("%d%d",&a,&b);
    printf("\nEnter the operation you desire to perform on Calculator and i.e +, -, *, /  :\n");
    // try give a space like " %c"
    scanf(" %c",&d);
    switch(d) {
        case '+': printf("\n%d %c %d =%d",a,d,b,(a+b));
            break;
        case '-': printf("\n%d %c %d =%d",a,d,b,(a-b));
            break;
        case '*': printf("\n%d %c %d =%d",a,d,b,(a*b));
            break;
        case '/': (a>b)?(printf("\n%d %c %d =%d",a,d,b,(a/b))):(printf("\n%d %c %d =%d",a,d,b,(b/a)));
            break;
        default: printf("\nInvalid input");
    }
    return 0;
}

它工作正常:)