2

I am creating a program that reads in values from an input file and stores them into a 2d array.. I can't figure out how to end the "read in" loop at the end of the file, because I'm using integers and EOF isn't an integer.

Currently it will create an infinite loop.

//      while(?????)
     {
            //printf("Test");
            fscanf(fp, "%d", &x);
            fscanf(fp, "%d", &y);
            fscanf(fp, "%d", &val);
            fscanf(fp, "%d", &val2);
            fscanf(fp, "%d", &price);
            grid[x][y] = 1;
            grid[y][x] = 1;
     }

SAMPLE FILE INPUT

0 3 300 305 20
0 4 300 313 20
0 5 300 306 20
0 2 300 301 20
1 0 301 302 20
1 5 304 308 8
1 4 310 315 20
2 5 312 324 30
Kijewski
  • 25,517
  • 12
  • 101
  • 143
Stanfrancisco
  • 352
  • 1
  • 7
  • 24

2 Answers2

3

As long as the fscanf reads five values, the while will continue and will stop when it reaches the end of the file.

while( ( fscanf ( fp, "%d %d %d %d %d", &x, &y, &val, &val2, &price)) == 5)
{
    grid[x][y] = 1;
    grid[y][x] = 1;
}
Kijewski
  • 25,517
  • 12
  • 101
  • 143
user3121023
  • 8,181
  • 5
  • 18
  • 16
-1

Use !feof(fp) as the condition for your while loop

fferri
  • 18,285
  • 5
  • 46
  • 95