2017-11-10 7 views
0

私は初心者であり、ファイルからデータを読み取り、オブジェクトにデータを格納しようとしています。以下は値を読み取る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. 

        } }}  

データをオブジェクトに直接読み込むための最良の方法を教えてください。

答えて

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

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

これは、次のファイルの内容のために動作します

関連する問題