Search code examples
while-loopprompt

How to reprompt in a while loop


 while(1)
{
     printf("Please enter the first number:\n");
     if(scanf(" %f",&num1))
       break;
}

I'm trying to re prompt the user for a integer value if they enter a character. when I run this code is creates an infinite loop. Im using c language


Solution

  • #include <stdio.h>  
    
    int clean_stdin()
    {
        while (getchar()!='\n');
        return 1;
    }
    
    int main(void)  
    { 
        int num1=0;  
        do
        {  
            printf("\nPlease enter the first number: ");
        } while ((scanf("%d", &num1)!=1 && clean_stdin()));
    
        return 0;  
    }
    

    Explanation

    The clean_stdin() function will be executed only if the entered value is a string containing a non-numeric character. And it will always return True, thus implying that the entered value is definitely a numeric value.

    For more info refer to this amazing answer