从文件 c++ 中读取 class 个对象

Read class objects from file c++

我需要从文件中读取 class 个对象,但我不知道如何读取。

这里我有一个class"People"

class People{
public:

string name;
string surname;
int years;
private:

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

现在我想从 .txt 文件中读取人物并将它们存储到 class 人物的对象中。

例如,我的 .txt 文件是这样的:

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

我认为最好的方法是创建包含 4 个对象的数组。我需要逐字逐行地阅读,如果我假设正确但我不知道如何...

这样做的方法是为您的class编写一个存储格式,例如,如果我这样做,我会像您一样存储信息

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

如果您不熟悉 vector 是什么,建议使用 vectors 来存储可以在 C++ 中动态增长的对象数组。 vector class 是 C++ 标准库的一部分。并且由于您是从文件中读取的,因此您不应该提前假设有多少对象将存储在文件中。

但以防万一您不熟悉我在上面示例中使用的 classes 和功能。这里有一些链接

矢量 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