You actually wanted
while (!feof(in))
instead of
while (feof! (in))
That too is wrong. See Why is while ( !feof (file) )
always wrong? to know why it is wrong.
Instead of that the correct way would be to use the return value of fscanf
as the condition. As per the C11 standard,
7.21.6.2 The fscanf function
[...]
- The
fscanf
function returns the value of the macro EOF
if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
So, in your case, fscanf
will return 1 if successful. Therefore, use
while(fscanf(in, "%d", &water_arr[monthnum])==1)
and remove the fscanf
from the body of this loop. To prevent array overruns, use
while(monthnum<30 && fscanf(in, "%d", &water_arr[monthnum])==1)
There is another problem too. Since water_arr
is a local, non-static
, int
array, it will not be initialized automatically. You, after reading data from the file, print the whole array. This will lead to Undefined Behavior if the number of integers read is less than 30. You should use a different variable and print the array indices until this variable becomes equal to monthnum
. Like:
int i;
for(i=0 ; i<monthnum ; i++)
printf("%d",water_arr[i]);
instead of
for (monthnum = 0; monthnum < 30; monthnum++)
{
printf("%d",water_arr[monthnum]);
}