scanf("%d/%d%c%d/%d", &num1, &denom1, &sign, &num2, &denom2); Keeps on scanning for user input at the console

Viewed 55

scanf("%d/%d%c%d/%d", &num1, &denom1, &sign, &num2, &denom2); keeps on scanning for user input at the console, no matter how many integers or characters I enter. The program does not proceed further. What is happening here?

By the way my code is as follows

#include<stdio.h>
//------------------------START OF MAIN()--------------------------------------
int main(void)
{
    printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
    
    int num1, denom1, num2, denom2, result_num, result_denom,flag=1;
    char sign;

    printf("Enter fraction1 operator fraction2(operators + - * /): ");
    scanf("%d/%d%c%d/%d", &num1, &denom1, &sign, &num2, &denom2);  //doesn't work. Won't stop taking inputs
         //three scanfs --for fraction1, operator, fraction2--also takes unlimited inputs.
         //A scanf to read fraction1, getchar to read operator and another scanf to read fraction2 works fine.
    //scanf("%d/%d", &num1, &denom1);
    //sign=getchar();
    //scanf("%d/%d",&num2, &denom2);
    
    switch(sign)
    {
        case '+':
            result_num = num1 * denom2 + num2 * denom1;
            result_denom = denom1 * denom2;
            break;
        case '-':
            result_num = num1 * denom2 - num2 * denom1;
            result_denom = denom1 * denom2;
            break;
        case '*':
            result_num = num1 * num2;
            result_denom = denom1 * denom2;
            break;
        case '/':
            result_num = num1 * denom2;
            result_denom = denom1 * num2;
            break;
        default:
            flag=0;
            printf("Invalid Operator.");
    }
    if(flag)
        printf("The result is %d/%d", result_num, result_denom);
    
    printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
    return 0;
}
//-------------------------END OF MAIN()---------------------------------------

The input I tried to enter is 31/8+7/4. And I press enter, but the program won't proceed further. If I use the following three statements viz, scanf(), getchar(), printf() instead (which are commented), I am able to execute the program without issues (as long as there is no line feed while entering the input). What is happening here?

0 Answers
Related