-4

The code looks almost identical to a previous assignment, however it does not compile.

The problem appears to be before the while(feof!(in))

error: expected ')' before '!' token

Code:

#include <stdio.h>

int main (void)
{
    int water_arr[30],monthnum=0;

    FILE* in;
    in = fopen ("water.txt","r");

    while (feof! (in))
        {
            fscanf(in, "%d", &water_arr[monthnum]);
            monthnum = monthnum + 1;
        }

    for (monthnum = 0; monthnum < 30; monthnum++)
        {
            printf("%d",water_arr[monthnum]);
        }

    return (0);
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • 3
    try explaining to a rubber duckie what each token does in `feof! (in)` – M.M Mar 22 '15 at 22:42
  • 2
    I think you mean `!feof(in)` instead of `feof! (in)`. – Hunter McMillen Mar 22 '15 at 22:42
  • 5
    once you've figured it out, [read this](http://stackoverflow.com/a/5432517/1505939) – M.M Mar 22 '15 at 22:43
  • 1
    Do not use `while (feof! (in))`. Check the return value of `fscanf()` to determine if code should quit the loop. Also quit loop once `monthnum` searches 30. Print loop should only go up to the number of values read, which may be less than 30. – chux - Reinstate Monica Mar 22 '15 at 23:40

1 Answers1

0

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

[...]

  1. 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]);
}
Community
  • 1
  • 1
Spikatrix
  • 20,225
  • 7
  • 37
  • 83