gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:49:28 25 4
gpt4 key购买 nike

我想从文件中读取 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

运算符>>代码:

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

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

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