0

I'm trying to read from a file following this tutorial: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-7-model-loading/

The problem is that when I try to copy the code and do fscanf, the values are always initialized to crazy values like -848228281 or something similar. The first time I read the values for the vertices it works, but not for the faces.

while (!(feof(fp)))
{
    read = fscanf(fp, "%c", &ch);       
    if (/*read == 4 && */ch == 'v')
    {
        // this works
        read = fscanf(fp, "%f %f %f\n", &x, &y, &z);
        vertices.push_back(vector3(x, y, z));
        //glVertex3f(x, y, z);
    }
    else if (ch == 'f')
    {
        GLint vertexIndex[3], uvIndex[3], normalIndex[3];

        // this line below does not work
        int matches = fscanf(fp, "%d/%d/%d %d/%d/%d %d/%d/%d\n",
            &vertexIndex[0], &uvIndex[0], &normalIndex[0],
            &vertexIndex[1], &uvIndex[1], &normalIndex[1],
            &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
        if (matches != 9)
        {
            printf("Incompatible file!");
            return;
        }
    }
}

My obj file is the same as in the tutorial.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 5
    It's hard telling what could be wrong without a [mcve]. – R Sahu Dec 03 '18 at 03:28
  • From the example it looks like an out-of-scope error. How do you get the values from `vertexIndex` `uvIndex` and `normalIndex` outside of the `else if` block? Since after this they will be invalid. – Yastanub Dec 03 '18 at 03:32
  • @Yastanub I put a breakpoint at if (matches != 9) and inspect the values in the watch window there. – joe doe Dec 03 '18 at 03:38
  • And are you sure you put the breakpoint in the correct line? What about `matches` what does it contain? And have you only encountert Problems in the watch window or are the values wrong past that point? – Yastanub Dec 03 '18 at 03:51
  • They are wrong past that point. I put a cout after the if statement as well. matches returns 0. – joe doe Dec 03 '18 at 03:54
  • 2
    If `matches` returns zero then that means `fscanf` didn’t find the information you wanted it to find and the values are undefined, as you’ve noticed. – Sami Kuhmonen Dec 03 '18 at 04:12
  • 2
    Unrelated: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – user4581301 Dec 03 '18 at 04:14

1 Answers1

0

The code will enter the else if (ch == 'f') { ... } clause when it encounters the line of data that reads:

s off

because of the 'f' characters. But the subsequent attempt to read the numeric values will fail (for obvious reasons).

Michael Burr
  • 333,147
  • 50
  • 533
  • 760