Meta
Meta

Reputation: 1753

scanf() misbehaving

I have a very short snippet that reads in 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 input any letter, it just keeps looping through and prints out 'No number found' instead of waiting for the next input.

What am I doing wrong?

Upvotes: 0

Views: 801

Answers (3)

Rahul Dimri
Rahul Dimri

Reputation: 305

Man page says

RETURN VALUES These functions return the number of input items assigned. This can be fewer than provided for, or even zero, in the event of a matching failure. Zero indicates that, although there was input available, no conversions were assigned; typ- ically this is due to an invalid input character, such as an alphabetic character for a `%d' conversion.

Since you have used "%d" , if you use any number then this will work fine otherwise it will not consume it from the buffer

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 373082

When using scanf, if you try doing a read operation and the data found doesn't match the expected format, scanf leaves the unknown data behind to be picked up by a future read operation. In this case, what's happening is that you're trying to read formatted data from the user, the user's data doesn't match your expected format, and so it fails to read anything. It then loops around to try to read again and finds the same offending input it had before, then loops again, etc.

To fix this, you just need to consume the characters that gummed up the input. One way to do this would be to call fgetc to read characters until a newline is detected, which will flush any offending characters:

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);
    }
}

Hope this helps!

Upvotes: 2

Joe
Joe

Reputation: 11677

Sounds like you are not clearing the input buffer and leaving the incorrect char to be scanned over and over.
See here:
Scanf and loops
and
scanf not terminating

Upvotes: 1

Related Questions