Scanf () does not work well

I have a very short fragment that is read as an integer:

#include <stdio.h>

int main() {
    while (1) {
        int i = 0;
        int r = scanf("%d", &i);

        if (r == EOF) {
            printf("Error using scanf()\n");
        } else if (r == 0) {
            printf("No number found\n");
        } else {
            printf("The number you typed in was %d\n", i);
        }
    }
}

but the problem is that if I enter any letter, it just continues the loop and displays "No number found" instead of waiting for the next input.

What am I doing wrong?

0
source share
3 answers

scanf, , , scanf , . , , , . , , , ..

, , . - fgetc , , :

while (1) {
    int i = 0;
    int r = scanf("%d", &i);

    if (r == EOF) {
        printf("Error using scanf()\n");
    } else if (r == 0) {
        printf("No number found\n");

        /* Consume bad input. */
        while (fgetc(stdin) != '\n')
            ;

    } else {
        printf("The number you typed in was %d\n", i);
    }
}

, !

+2

, char .
. :


scanf

+1

""

    . , , ,     . Zero , , , ; typ-     , % d.

"% d", , , .

0

All Articles