在这个C程序中,第二个scanf被跳过,如果我使用fflush然后它工作正常。为什么会这样? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

在这个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

c scanf
1个回答
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;
}

它工作得很好:)

© www.soinside.com 2019 - 2024. All rights reserved.