简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM