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);
}
}
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments