简体   繁体   中英

Infinite loop when assigning a float to an integer

Please i'm having an issue with my program. Whenever i try to input a float it's getting into an infinity loop. I know that the input is stored as an integer. How can prevent the user from entering a float (how to filter the input).

Why is the program getting into an infinite loop when the input is a float.

This is an example:

#include <stdio.h>

main()
{
    int i = 0;
    while(i<10){
        system("cls>null");
        printf("%d^2 = %d\n", i, i*i);

        printf("Index: ");
        scanf("%d", &i);
    }
}

Better use fgets() to read a complete line from stdin, and strtol() to parse it into an number, for example:

char buffer[256];
char *endp;
int i;
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
    // buffer now contains one line (including the terminating newline)
    i = (int)strtol(buffer, &endp, 10);
    // endp points to the first character after the parsed number:
    if (endp > buffer && (*endp == 0 || isspace(*endp))) {
        printf("%d^2 = %d\n", i, i*i);
    } else {
        printf("invalid input\n");
    }
}

When you call scanf to read a number, but the input contains something incompatible with the input format specifier, scanf does not consume such incorrect input, leaving it in the buffer. Your program does not clear the buffer on input mismatch, entering an infinite loop: scanf tries to read an int again, sees that it's not there, and exits without modifying i . Your loop sees that i is less than 10, and calls the scanf again.

To fix this, check that scanf returned one input. Use the input when it is correct, or call scanf again with the %*[^\\n]\\n specifier, which means "read to the end of the string, and discard the input":

if (scanf("%d", &i) != 1) {
    scanf("%*[^\n]\n");
}

Note the asterisk - it means that the consumed input needs to be discarded, rather than being written into a variable.

#include <math.h>
#include <stdio.h>

int main (void)
{
    int i = 0;
    float j = 0;
    while(i<10)
    {
        system("cls");
        printf("%d^2 = %d\n", i, i*i);

        printf("Index: ");
        if (scanf("%f", &j) <= 0 && j-fabs(j) != 0)
        {
             printf ("The input is not an interger");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM