在 c++ 中从数据文件中读取值对象
Reading Values Object wise from data file in 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
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";
这将适用于以下文件内容
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中