1
 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

Jackie
  • 9
  • 2

1 Answers1

1
#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

theWellHopeErr
  • 1,856
  • 7
  • 22