C++ 从c++;

C++ 从c++;,c++,C++,我是初学者,尝试从文件中读取数据并将数据存储到对象中 以下是我的文件结构: #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

我是初学者,尝试从文件中读取数据并将数据存储到对象中

以下是我的文件结构:

 #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
下面是我的班级结构

class Mat {
public:
    Mat();
    Mat(Color& r, Color& g, Color& b, int s);
private:
    Color r;
    Color g; 
    Color b; 
    int n;
我试着这样做

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.

                    } }}    
vectormat;//可供选择的
垫温;
弦线;
if(file.is_open())
{
while(getline(文件,行))
{
文件>>材料>>材料计数;
文件>>lit>>litCount;
文件>>对象>>对象计数;
对于(int i=0;i>tempMat.mat;
//在这里,我面临着一个问题。
} }}    
您能告诉我什么是将数据直接读入对象的最佳方式吗

vector<Mat> mat;
...
file >> mat >> matCount;
逐行读取文件。将每行转换为流。将流读入临时
。将临时
Mat
添加到向量。例如:

#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";
#包括
#包括
#包括
#包括
...
班垫
{
公众:
字符串名;
重瓣的红色,绿色,蓝色;
};
向量矩阵;
弦线;
while(getline(文件,行))
{
弦流ss(线);
垫温;
如果(ss>>温度名称>>温度红色>>温度绿色>>温度蓝色)
{
库特
#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";