0

I am Beginner and trying to read data from a file and store data into object.

Below are my file structure:

 #mat 4    //count of mat type of objects
 #lit 1
 #obj 4     //count of objects in scene

mat                     //mat object
ka   0.5 0.5 0.5
kd   1 0 0
ks   1 1 1
sh   10 

lit                    //lit object
color    1 0.7 0.7
pos -10 10 10

triangle                //scene object
v1   1 0 0
v2   0 1 0
v3   0 0 1
mat 0

And Below are my class mat class structure

class Mat {
public:
    Mat();
    Mat(Color& r, Color& g, Color& b, int s);
private:
    Color r;
    Color g; 
    Color b; 
    int n;

I tried to do like this.

vector<Mat> mat; // list of available 
Mat temp;
string line;


 if (file.is_open())
            {
                while (getline(file, line))
                {
                    file >> mat >> matCount;
                    file >> lit>> litCount;
                    file >> object >> objectCount;
                    for (int i = 0; i < matCount; i++)
                    {
                     file>>tempMat.mat;
                      //here I am facing problem.

                    } }}    

could you please suggest me what is the best way to directly read data into object.

0

1 Answer 1

1
vector<Mat> mat;
...
file >> mat >> matCount;

mat is a vector, file >> mat will not work.

If your file content is the following:

mat
ka   0.5 0.5 0.5
kd   1 0 0
ks   1 1 1
triangle
tka   0.5 0.5 0.5
tkd   1 0 0
tks   1 1 1

Read the file line by line. Convert each line to stream. Read the stream in to a temporary Mat. Add the temporary Mat to the vector. Example:

#include <string>
#include <vector>
#include <fstream>
#include <sstream>
...

class Mat
{
public:
    string name;
    double red, green, blue;
};

vector<Mat> mat;
string line;
while(getline(file, line))
{
    stringstream ss(line);
    Mat temp;
    if(ss >> temp.name >> temp.red >> temp.green >> temp.blue)
    {
        cout << "A " << temp.name << endl;
        mat.push_back(temp);
    }
    else
    {
        cout << "Error: " << line << endl;
    }
}

for(auto e : mat)
    cout << e.name << ", " << e.red << ", " << e.green << ", " << e.blue << "\n";

This will work for the following file content

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.