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

后端 未结 16 1704
日久生厌
日久生厌 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 06:55

    When a non-number is entered an error occurs and the non-number is still kept in the input buffer. You should skip it. Also even this combination of symbols as for example 1a will be read at first as number 1 I think you should also skip such input.

    The program can look the following way.

    #include 
    #include 
    
    int main(void) 
    {
        int p = 0, n = 0;
    
        while (1)
        {
            char c;
            int number;
            int success;
    
            printf("-> ");
    
            success = scanf("%d%c", &number, &c);
    
            if ( success != EOF )
            {
                success = success == 2 && isspace( ( unsigned char )c );
            }
    
            if ( ( success == EOF ) || ( success && number == 0 ) ) break;
    
            if ( !success )
            {
                scanf("%*[^ \t\n]");
                clearerr(stdin);
            }
            else if ( number > 0 )
            {
                ++p;
            }
            else if ( number < n )
            {
                ++n;
            }
        }
    
        printf( "\nRead %d positive and %d negative numbers\n", p, n );
    
        return 0;
    }
    

    The program output might look like

    -> 1
    -> -1
    -> 2
    -> -2
    -> 0a
    -> -0a
    -> a0
    -> -a0
    -> 3
    -> -3
    -> 0
    
    Read 3 positive and 3 negative numbers
    

提交回复
热议问题