从c ++中的数据文件中读取对象

时间:2017-11-10 03:48:20

标签: c++

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

以下是我的文件结构:

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.

                    } }}    

我试着这样做。

remove_keys = ['exit', 'get_ipython']
g = sorted(
        dict(
            (k,v) for k,v in globals() 
            if k not in remove_keys
        )
    )

您能不能建议我将数据直接读入对象的最佳方法是什么。

1 个答案:

答案 0 :(得分:1)

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

mat是一个向量,file >> mat将不起作用。

如果您的文件内容如下:

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

逐行读取文件。将每一行转换为流。将流读入临时Mat。将临时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";

这适用于以下文件内容