-1

In this C program, if I use fflush(stdin) before the second scanf, then it's working fine. And also scanning the operator before the operands, then it's working. I don't understand, why it's working like that.

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

Output:

enter image description here

karel
  • 5,489
  • 46
  • 45
  • 50

1 Answers1

0

Just modify your code to this :

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

It is working fine :)

Anish B.
  • 9,111
  • 3
  • 21
  • 41