4

I'm trying to read from a file that has the format:

 ID: x y z ...... other crap 

The first line looks like this:

 0: 0.82 1.4133 1.89 0.255 0.1563 armTexture.jpg 0.340 0.241 0.01389

I only need the x y z float numbers, the rest of the line is garbage. My code currently looks like this:

int i;
char buffer[2];
float x, y, z;

FILE* vertFile = fopen(fileName, "r");      //open file
fscanf(vertFile, "%i", &i);                 //skips the ID number
fscanf(vertFile, "%[^f]", buffer);      //skip anything that is not a float (skips the : and white space before xyz)

//get vert data
vert vertice = { 0, 0, 0 };
fscanf(vertFile, "%f", &x);
fscanf(vertFile, "%f", &y);
fscanf(vertFile, "%f", &z);

fclose(vertFile);

It's been changed a little for debugging (originally the first two scanfs used * to ignore the input).

When I run this, x, y, z do not change. If I make it

int result = fscanf(vertFile, "%f", &x);

result is 0, which I believe tells me it isn't recognizing the numbers as floats at all? I tried switching xyz to doubles and using %lf as well, but that didn't work either.

What could I be doing wrong?

  • 3
    Where did you get the idea that `%[^f]` skipped over non-floats? – Steve Summit Oct 24 '19 at 21:13
  • Welp, I was kinda using this: https://stackoverflow.com/questions/2799612/how-to-skip-the-first-line-when-fscanning-a-txt-file – SloanTheSloth Oct 24 '19 at 21:15
  • But I just realized that I'm an idiot because he was using it to skip over anything that's not the new line character. I'm not sure why my brain thought it would work for %f lmao. – SloanTheSloth Oct 24 '19 at 21:15
  • 2
    You should read the entire line with `fgets` and then use `sscanf` to extract the three numbers. – user3386109 Oct 24 '19 at 21:18

1 Answers1

5

%[^f] doesn't skip non-floats, it skips anything that's not the letter 'f'.

Try %*d: instead. * discards the number read, and a literal : tells it to skip over the colon. You can also combine all those individual reads.

fscanf(vertFile, "%*d: %f %f %f", &x, &y, &z);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578