The problem of protecting the program in case of invalid input is as old as programming, and I've found many questions about that on this site, however nothing helped me in my case.
I've got a function which loads values into a float two-dimensional array.
void load_val(
float matrix[MAX_SIZE][MAX_SIZE],
const int line_num,
const int column_num
)
{
for (int i=0; i<line_num; ++i)
{
printf("Give number\n");
for (int j=0; j<column_num; ++j)
{
scanf("%f", &matrix[i][j]);
}
}
}
And obviously, when the user types in a letter, the program goes into an infinite loop.
I used two solutions to that problem and neither worked.
First one is using the fact that scanf returns 0 when there's invalid input.
So instead of
scanf("%f", &matrix[i][j]);
I wrote
while (scanf("%f", &matrix[i][j])==1);
But it still gives me an infinite loop.
The other solution was just using "isdigit" function.
int h = scanf("%f", &matrix[i][j]);
if (isdigit(h)==0)
{
puts("INVALID");
j--;
}
but I really don't want to use other libraries and it also did not work. The problem seems to be that before I can even check if the input is valid, the program goes crazy because of the input.
I even tried this
float h;
if (scanf("%f", &h)==1)
{
matrix[i][j]=h;
}
else
{
puts("INVALID");
j--;
};
Still - infinite loop.
How can I check for invalid input in this loop-inside-a-loop before the program goes crazy?. Is the problem with the float type maybe?
fgetsto get the input in a string. Then parse the string to check for floats. If you get an unwanted character, you can skip it, or warn the user.isdigitis as wrong as it could possibly be. Especially since you seem to know whatscanfreturns. It's also a standard C function, so no "other libraries" will be used.