从文件 c++ 读取对象

Read objects from file c++

本文关键字:取对象 读取 c++ 文件      更新时间:2023-10-16

我想从文件中读取 3 个对象。例如,在主要我写道:

ifstream fis;
Person pp;
fis >> pp;
Person cc;
fis >> cc;
Person dd;
fis >> dd;

问题是,对于每个人,它都会给我读 3 个对象。我需要创建一个对象数组?

ifstream& operator>>(ifstream&fis, Person &p){
    fis.open("fis.txt", ios::in);
    while (!fis.eof())
    {
        char temp[100];
        char* name;
        fis >> temp;
        name = new char[strlen(name) + 1];
        strcpy(name, temp);
        int age;
        fis >> age;

        Person p(name, age);
        cout << p;
    }
    fis.close();
    return fis;
}

问题:

您正在打开和关闭operator>>内的输入流。因此,每次执行它时,它都会在开头打开您的文件,然后读取到末尾并再次关闭文件。在下一次通话时,它又重新开始。

解释:

使用的输入流会跟踪其当前的读取位置。如果在每次调用中重新初始化流,则会重置文件中的位置,从而重新开始。如果你有兴趣,你也可以用std::ifstream::tellg()检查位置。

可能的解决方案:

operator>> 之外准备输入流,然后每次调用只需读取一个数据集。完成所有读取后,关闭外部的文件。

例:

电话代码:

#include<fstream>
// ... other code
std::ifstream fis;
Person pp, cc, dd;
fis.open("fis.txt", std::ios::in); // prepare input stream
fis >> pp;
fis >> cc;
fis >> dd;
fis.close(); // after reading is done: close input stream

operator>>代码:

std::ifstream& operator>>(std::ifstream& fis, Person &p)
{
    // only read if everything's allright (e.g. eof not reached)
    if (fis.good())
    {
        // read to p ...
    }
    /*
     * return input stream (whith it's position pointer
     * right after the data just read, so you can start
     * from there at your next call)
     */
    return fis;
}

在使用operator>>之前,您应该准备要从中读取的流。

ifstream fis;
fis.open("fis.txt", ios::in);
Person pp;
fis >> pp;
Person cc;
fis >> cc;
Person dd;
fis >> dd;
fis.close();

您的代码应如下所示。

ifstream& operator>>(ifstream&fis, Person &p) {
    char temp[100];
    char* name;
    fis >> temp;
    name = new char[strlen(name) + 1];
    strcpy(name, temp);
    int age;
    fis >> age;
    Person p(name, age);
    cout << p;
    return fis;
}

如果流不为空,请考虑添加其他检查,并使用 string s 而不是 char*