Ad

Infinite Loop In C When The User Enters A Character Instead Of A Number

- 1 answer

I have a problem, I want to make the user enter a digit from 1.00 to 10.00 and if he enters a digit outside of that range I will display that he was wrong and try again. I think I have done well but the problem is if the user enters a letter the loop repeats at infinity, I would appreciate your help. Thank you. :)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    float a;

    do
    {
        printf("Insert number between 1.00 and 10.00:\n");
        scanf("%f", &a);

        if (a < 1.00 || a > 10.0)
        {
            printf("Insert a correct number.\n");
        }
    } while (a < 1.00 || a > 10.00);

    system("pause");
    return 0;
}
Ad

Answer

scanf leaves the '\n' char in the input stream so you need to skip it:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    float a;

    do
    {
        printf("Insert number between 1.00 and 10.00:\n");
        scanf(" %f", &a);

        if (a < 1.00 || a > 10.0)
        {
            printf("Insert a correct number.\n");
        }
    } while (a < 1.00 || a > 10.00);

    printf("\nyou have entered: %f\n", a);

    return 0;
}

https://godbolt.org/z/baPxdn .But it does not sort out the wrong input problem.

I personally prefer to read the line and then scan it (and it does sort all the problems out):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    char str[100];
    float a;

    do
    {
        printf("Insert number between 1.00 and 10.00:\n");
        fgets(str, 100, stdin);
        if(sscanf(str, " %f", &a) != 1) continue;

        if (a < 1.00 || a > 10.0)
        {
            printf("Insert a correct number.\n");
        }
    } while (a < 1.00 || a > 10.00);

    printf("\nyou have entered: %f\n", a);

    return 0;
}

https://godbolt.org/z/vxY7To

Ad
source: stackoverflow.com
Ad