gpt4 book ai didi

c++ - 从文件中读取类对象 C++

转载 作者:行者123 更新时间:2023-11-30 02:31:32 25 4
gpt4 key购买 nike

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

这里我有一个类“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 文件中读取 peoples 并将它们存储到 People 类的对象中。

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

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

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

最佳答案

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

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 是什么,vector 是在 C++ 中存储可动态增长的对象数组的推荐方法。 vector 类是 C++ 标准库的一部分。并且由于您是从文件中读取的,因此您不应该提前假设有多少对象将存储在文件中。

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

vector 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

关于c++ - 从文件中读取类对象 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37532631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com