Search code examples
cscanfgetchar

How to error check when entering a float in c?


I have a program that prompts the user for an integer that is not negative or character. I want to prompt the user for a float instead. How do i do this?

do {
    printf("Enter a number.\n");  
} while(((scanf("%d%c", &x1, &term) != 2 || term != '\n') 
          && reset_stdin()) || x1 < 1);

int reset_stdin()
{
    while (getchar()!='\n');
    return 1;
}

Solution

  • To use scanf with a float, just use the "%f" format specifier.

    float input;
    scanf("%f", &input);