Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

.obj

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?

like image 288
Xiconaldo Avatar asked Jan 22 '26 06:01

Xiconaldo


1 Answers

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];
like image 122
Shafik Yaghmour Avatar answered Jan 24 '26 18:01

Shafik Yaghmour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!