Reading and storing values from .OBJ files using C++
Solution 1
As I mentioned in my comment, you read one line with:
getline (myfile,line);
and then if the line has v
in the first position you read another line with this statement:
myfile >> v >> valuesX[n]>> valuesY[n]>> valuesZ[n];
but you do not process the previous line read in with the getline
so you will lose that line. One possible solution is to process each line
that matches using istringstraeam
:
std::istringstream iss( line );
iss >> v >> valuesX[n]>> valuesY[n]>> valuesZ[n];
Solution 2
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.
Xiconaldo
Updated on June 07, 2022Comments
-
Xiconaldo almost 2 years
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?