Why is scanf() causing infinite loop in this code?

后端 未结 16 1491
日久生厌
日久生厌 2020-11-21 06:20

I\'ve a small C-program which just reads numbers from stdin, one at each loop cycle. If the user inputs some NaN, an error should be printed to the console and the input pro

16条回答
  •  無奈伤痛
    2020-11-21 07:19

    To solve partilly your problem I just add this line after the scanf:

    fgetc(stdin); /* to delete '\n' character */
    

    Below, your code with the line:

    #include 
    
    int main()
    {
        int number, p = 0, n = 0;
    
        while (1) {
            printf("-> ");
            if (scanf("%d", &number) == 0) {
                fgetc(stdin); /* to delete '\n' character */
                printf("Err...\n");
                continue;
            }
    
            if (number > 0) p++;
            else if (number < 0) n++;
            else break; /* 0 given */
        }
    
        printf("Read %d positive and %d negative numbers\n", p, n);
        return 0;
    }
    

    But if you enter more than one character, the program continues one by one character until the "\n".

    So I found a solution here: How to limit input length with scanf

    You can use this line:

    int c;
    while ((c = fgetc(stdin)) != '\n' && c != EOF);
    

提交回复
热议问题