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

Reading Values Object wise from data file in c++

本文关键字:读取 文件 对象 数据 c++      更新时间:2023-10-16

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

以下是我的文件结构:

 #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.
                    } }}    

您能否建议我将数据直接读取到对象中的最佳方法是什么。

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";

这将适用于以下文件内容