C : while( scanf("%d",&num) != 1 ) infinite loop

hope you could help me with this
I have to use scanf to read and validate inputs…
I’ve tried this code:

int num = 0;
while( scanf("%d",&num) != 1 || num < 3 || num > 9){
printf("Enter new num: ");
}

when I input numbers it works great but when I input any other character it goes into infinite loop instead of asking for new input…

Enter new num: Enter new num: Enter new num: Enter new num:
Enter new num: Enter new num: Enter new num: Enter new num:
Enter new num: Enter new num: Enter new num: Enter new num:

any ideas?

thanks

>Solution :

You need to remove the invalid data from the input buffer. for example

int num = 0;
while( scanf("%d",&num) != 1 || num < 3 || num > 9){
    scanf( "%*[^\n]%*c" );
    printf("Enter new num: ");
}

Here is a demonstration program.

#include <stdio.h>

int main( void )
{
    int num = 0;

    printf("Enter new num: ");
    
    while( scanf("%d",&num) != 1 || num < 3 || num > 9){
        scanf( "%*[^\n]%*c" );
        printf("Enter new num: ");
    }
    
    printf("num = %d\n", num );
}

The program output might look like

Enter new num: 1
Enter new num: A
Enter new num: 10
Enter new num: 5
num = 5

Leave a Reply