从文件中读取对象 C++

Read objects from file c++

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

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 代替 char*

,请考虑添加额外的检查