Reading and storing values from .OBJ files using C++

Xiconaldo picture Xiconaldo · May 20, 2013 · Viewed 11.8k times · Source

First, sorry for bad english. Well, I'm trying read the values of a .OBJ file (see here) and storing them in variables using this program:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
string line;
string v, valuesX[8], valuesY[8], valuesZ[8];
int n = 0;

ifstream myfile ("cubo.obj");
while(!myfile.eof())
{
    getline (myfile,line);
    if (line[0] == 'v')
    {
        myfile >> v >> valuesX[n]>> valuesY[n]>> valuesZ[n];
        cout << valuesX[n] << "\t" << valuesY[n] << "\t" << valuesZ[n] << endl;
        n++;
    }
}
return 0;
}

The file it's only a simple cube, exported by Blender. I expected him to show me all lines beginning with "v", but the result presents only the odd "v" lines. When I read directly the value of the variable "line", the result is the same. However, when I remove the line that assigns values ​​to variables "value" and read the variable "line" directly, the program works perfectly. Anyone know explain to me what is happening? Why the program is ignoring the even lines?

Answer

user123 picture user123 · May 20, 2013

You're reading 2 lines per loop:

First time:

getline(myfile, line);

Second time:

myfile >> v >> valuesX[n] >> valuesY[n] >> valuesZ[n];

So you're discarding half your data.

Solution: Try using the ifstream::peek function to see if a line begins with a 'v', then you would read all the values into your variables.