2016-05-30 12 views
1

ファイルからクラスオブジェクトを読み込む必要がありますが、どのようにすればよいかわかりません。ここでファイルからクラスオブジェクトを読み込みC++

私は今、私は.txtファイルから人々を読んで、クラスの人々のオブジェクトにそれらを保存したい

class People{ 
public: 

string name; 
string surname; 
int years; 
private: 

People(string a, string b, int c): 
name(a),surname(b),years(c){} 
}; 

クラス「人」を持っています。例えば

、これは私の.txtファイルがどのように見えるかです:

John Snow 32 
Arya Stark 19 
Hodor Hodor 55 
Ned Stark 00 

私はこれを行うための最善の方法は、4つのオブジェクトの配列を作成することだと思います。私は正しく言えば、単語や行単位で単語を読む必要がありますが、私は正しく考えていますが、私はどのように分かっていませんか...

+2

使用 'のstdのために基づいて、いくつかのリンクがあります: :ifstream' + std :: getlineで各行を読み込み、std :: stringstreamで各行を解析します。 – marcinj

+0

この場合、 'operator >>'を読み込む方が簡単だと思います – Curious

答えて

3

これを行う方法は、これを行うには、私はあなたが以下の

行うことができ、それをファイルに書き込むには、次の

ifstream fin; 
fin.open("input.txt"); 
if (!fin) { 
    cerr << "Error in opening the file" << endl; 
    return 1; // if this is main 
} 

vector<People> people; 
People temp; 
while (fin >> temp.name >> temp.surname >> temp.years) { 
    people.push_back(temp); 
} 

// now print the information you read in 
for (const auto& person : people) { 
    cout << person.name << ' ' << person.surname << ' ' << person.years << endl; 
} 

を行うことができますでこれを読むには

John Snow 32 
Arya Stark 19 
Hodor Hodor 55 
Ned Stark 00 

を行ったような情報を格納しますし、

static const char* const FILENAME_PEOPLE = "people.txt"; 
ofstream fout; 
fout.open(FILENAME_PEOPLE); // be sure that the argument is a c string 
if (!fout) { 
    cerr << "Error in opening the output file" << endl; 

    // again only if this is main, chain return codes or throw an exception otherwise 
    return 1; 
} 

// form the vector of people here ... 
// .. 
// .. 

for (const auto& person : people) { 
    fout << people.name << ' ' << people.surname << ' ' << people.years << '\n'; 
} 

vectorvectorであることに慣れていない場合は、C++で動的に拡張できるオブジェクトの配列を格納するための推奨される方法です。 vectorクラスは、C++標準ライブラリの一部です。また、ファイルから読み込んでいるので、ファイルに保存されるオブジェクトの数を事前に想定してはいけません。

しかし、上記の例で使用したクラスと機能に慣れていない場合に備えて、ここで

ベクトルhttp://en.cppreference.com/w/cpp/container/vector

はifstreamhttp://en.cppreference.com/w/cpp/io/basic_ifstream

範囲がループhttp://en.cppreference.com/w/cpp/language/range-for

自動http://en.cppreference.com/w/cpp/language/auto

関連する問題