Scanf is not scanning

2020-01-28 14:31发布

问题:

I wrote a program using switch case statement and asked for a char for input but it does not ask for the char in the console window but skips it completely

int main() 
{
    float a, b, ans;
    char opr;

    printf("\nGIVE THE VALUES OF THE TWO NUMBERS\n");
    scanf(" %f %f",&a,&b);


    printf("\nGIVE THE REQUIRED OPERATOR\n");   

    //no display(echo) on the screen
    //opr = getch();
    //displays on the screen
    //opr = getche();

    scanf("%c",&opr);

    switch(opr)
    {
        case '+' :
            ans = a+b;
            printf("%f", ans);
            break;          
        case '-' :
            ans = a-b;
            printf("%f", ans);
            break;          
        case '*' :
            ans = a*b;
            printf("%f", ans);
            break;          
        case '/' :
            ans = a/b;
            printf("%f", ans);
            break;
        case '%' :
            ans = (int)a % (int)b;
            printf("%f", ans);
            break;
        default :
            printf("\nGIVE A VALID OPRATOR\n");

    }

    system("pause");        
    return 0;

but when i put a space before %c in the second scanf it works someone was telling something about a whitespace which i found confusing

He said the second scanf is taking the value of \n as a character and if i put a space before %c in the second scanf isn't that a character and doesn't it take the space as the character?

But in this program it does not take the \n as the character

int main() 
{
    char a;
    printf("\ngive a char\n");
    scanf("%c",&a);
    printf("%c",a);

    return 0;
}  

This is really confusing can any on help me i want to learn what is wrong.

回答1:

Every time you use scanf with this format :

scanf("%c",&a); 

it leaves a newline which will be consumed in the next iteration. Th last program that you mentioned have only one "scanf". try to use another scanf. you will get the same problem.

so to avoid white spaces you have to write :

 scanf(" %c",&opr); 

the space before the format string tells scanf to ignore white spaces. Or its better to use

getchar();

It will consume all your newline



回答2:

The problem is that you are leaving the \n entered after the numbers unconsumed and then is read by the second scanf(). If you check the value in opr you'll see it's '\n'.



回答3:

The second program do take the \n as the character.
Maybe you simply didn't input \n before inputting other characters.

example ( %c in printf is changed to %d to make it clear)



回答4:

Try adding fflush(stdin) before scanf.