0

I have the following dataset:

0 1
0 3
1 1
2 3
<empty line>

My goal is to read these points into two integers, x, and y. Obiviously, I do not want to read in the blank line at the end of the file, so I wrote the following code to avoid that.

#include <stdio.h>
#include <math.h>

int main() {
  FILE *input;
  int x, y;
  const float r = 2;

  input = fopen("coords.dat", "r");

  for (;;) {
    int nread = fscanf(input, "%i %i\n", &x, &y);
    if (!(nread >= 1)) break;
    fscanf(input, "%i %i\n", &x, &y);
    printf("%i %i\n", x, y);

  }

  fclose(input);

}

Essentially, if a line is blank, I break out of the loop. I know for a fact that my .dat file has a blank line at the end. However, I get the following output:

0 3
2 3

Evidently, this code is skipping every other line. Why is this happening?

quanticbolt
  • 117
  • 5
  • Note that the `\n` at the end of the format is a bad idea; see [`scanf()` — trailing white space in format string](https://stackoverflow.com/questions/15740024/) – Jonathan Leffler Dec 11 '17 at 02:00

1 Answers1

3

You are doing the fscanf twice but printing only at the end. You should remove the second fscanf from the for loop

Sudhee
  • 151
  • 4
  • 10