scanf() not taking input from console [closed]

2019-10-02 09:24发布

问题:

#include<stdio.h> 

int main() {

    float a, b, r;
    char op;

    scanf("%f",&a);
    scanf("%c",&op);
    scanf("%f",&b);
    scanf("%f",&r);

    switch(op) {

        case '+':
            r = a + b;
            printf("%f", r);
        break;

        case '-':
            r = a - b;     
            printf("%f", r);     
        break;

        case '*':
            r = a * b;    
            printf("%f", r);     
        break;

        case '/':
            r = a / b;     
            printf("%f", r);     
        break;

        default:
            printf ("Nekaj ne delas prav");

    }

    return 0;

}

it is giving output

"Nekaj ne delas prav"

and not taking any input. instead of using 'scanf()'and why it directly gives default value as output instead of using switch statement.

回答1:

In your code, please change

scanf("%f",&a);
scanf("%c",&op);
scanf("%f",&b);
scanf("%f",&r);

to

scanf("%f",&a);
scanf(" %c",&op);  //notice here
scanf("%f",&b);
scanf("%f",&r);

Without the leading space before %c, the \n stoted by previous ENTER key press after previous input, will be read and considered as valid input for %c format specifier. So, the second scanf() will not ask for seperate user input and the flow will continue to the third scanf().

The whitespace before %c will consume all leading whitespace like chars, including the \n stoted by previous ENTER key press and will consider only a non-whitespace input.

Note:

  1. %f format specifier reads and ignores the leading \n, so in that case, you don't need to provide the leading space before %f explicitly.

  2. The signature of main() is int main(void).



回答2:

Change:

scanf("%c", myNothing);

to:

scanf("%c", &myNothing);

Or better yet:

myNothing = getchar();

Also, make sure you have compiler warnings enabled.



标签: c scanf