SloanTheSloth
SloanTheSloth

Reputation: 43

fscanf not reading/recognizing float numbers?

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?

Upvotes: 4

Views: 346

Answers (1)

John Kugelman
John Kugelman

Reputation: 361585

%[^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);

Upvotes: 5

Related Questions