scanf() misbehaving

前端 未结 3 408
野性不改
野性不改 2020-12-22 06:07

I have a very short snippet that reads in an integer:

#include 

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


        
3条回答
  •  粉色の甜心
    2020-12-22 06:33

    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!

提交回复
热议问题