Flávio Sousa Flávio Sousa - 2 months ago 21
C Question

Stuck in infinite fgets loop

I'm trying to get a integer input, and I tried the most elementary method I could find. However, whenever something isn't a integer, it gets stuck in a infinite loop. I believe it's caused by the fgets funcion. I tried a few solutions I found on this site, but none worked. The code is as follows

int getint()
{
int number;
char input[4];

fgets(input, 4, stdin);
while ( atoi(input) < 0 || ( strcmp(input, "0") != 0 && atoi(input) == 0 ) )
printf("Insert a non negative number: ");
fgets(input, 4, stdin);
number = atoi(input);
printf("%d\n", number);

return number;
}

Answer

If there are more than one statements that you want to write in a loop or if statement, then you must use braces {} to define which statements come in the loop.

In your code, only the printf("Insert a non negative number: "); statement is in the loop, and nothing is changing the input's value in the loop, so if the loop's condition is true, it will always remain true.

Change it to:

while ( atoi(input) < 0 || ( strcmp(input, "0") != 0 && atoi(input) == 0 ) )
{
    printf("Insert a non negative number: ");
    fgets(input, 4, stdin);
}
Comments