Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading