Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

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

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("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
");
    
    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("
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
");
    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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...