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

后端 未结 16 1470
日久生厌
日久生厌 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:08

    Hi I know this is an old thread but I just finished a school assignment where I ran into this same problem. My solution is that I used gets() to pick up what scanf() left behind.

    Here is OP code slightly re-written; probably no use to him but perhaps it will help someone else out there.

    #include 
    
        int main()
        {
            int number, p = 0, n = 0;
            char unwantedCharacters[40];  //created array to catch unwanted input
            unwantedCharacters[0] = 0;    //initialzed first byte of array to zero
    
            while (1)
            {
                printf("-> ");
                scanf("%d", &number);
                gets(unwantedCharacters);        //collect what scanf() wouldn't from the input stream
                if (unwantedCharacters[0] == 0)  //if unwantedCharacters array is empty (the user's input is valid)
                {
                    if (number > 0) p++;
                    else if (number < 0) n++;
                    else break; /* 0 given */
                }
                else
                    printf("Err...\n");
            }
            printf("Read %d positive and %d negative numbers\n", p, n);
            return 0;
        }
    

提交回复
热议问题