cscanfdo-loops

why does the do while skip scanf when none digit character is inputted


In c I have this snippet

    int n=0; 
    do {
        printf("random text\n");
        scanf("%d", &n); 
    } while ( n < 1 || n > 10);

when the user inputs anything other than a number the loop spams the printf without waiting for user input

why does this happen and how do I fix this


Solution

  • You need to skip the current content of the buffer if it does not contain a valid number. For example

    int n=0; 
    do {
        printf("random text\n");
        if ( scanf("%d", &n) == 0 )
        {
            scanf( "%*[^\n]" );
        }    
    } while ( n < 1 || n > 10);
    

    Pay attention to that this prompt

        printf("random text\n");
    

    is confusing when you expect from the user to enter a number.

    In general you should also add a check for EOF. For example

    int result = 1;
    int n=0; 
    do {
        n = 0;
        printf("random text\n");
    
        result = scanf("%d", &n);
    
        if ( result == 0 )
        {
            scanf( "%*[^\n]" );
        }
        else if ( result == EOF )
        {
            break;
        }  
    } while ( n < 1 || n > 10);
    
    if ( result == EOF ) exit( 1 );
    //...