从文件c ++

时间:2016-05-30 19:37:57

标签: c++ class readfile

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

这里我有一个班级“人物”

class People{
public:

string name;
string surname;
int years;
private:

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

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

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

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

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

1 个答案:

答案 0 :(得分: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';
}

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

但是,如果您不熟悉我在上面的示例中使用的类和功能。这是一些链接

vector http://en.cppreference.com/w/cpp/container/vector

ifstream http://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