2016-05-30 95 views
1

我需要从文件读取类对象,但我不知道如何。从文件读取类对象C++

在这里,我有一个类“人”

class People{ 
public: 

string name; 
string surname; 
int years; 
private: 

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

现在我想读txt文件人民,并将它们存储到一个阶层的人的对象。

举例来说,这是我的.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

要做到这一点的方法是组成你的类的存储格式,例如,如果我被做到这一点,我将存储就像你一样

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

要在你读这可以做到以下几点

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

把它写到你可以做以下

一个文件中的信息
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

ifstream的http://en.cppreference.com/w/cpp/io/basic_ifstream

一系列基于for循环http://en.cppreference.com/w/cpp/language/range-for

汽车http://en.cppreference.com/w/cpp/language/auto