我想从文件中读取 3 个对象。例如,我在 main 中写道:
ifstream fis;
Person pp;
fis >> pp;
Person cc;
fis >> cc;
Person dd;
fis >> dd;
Run Code Online (Sandbox Code Playgroud)
问题是,对于每个 Person,它都会读取 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;
}
Run Code Online (Sandbox Code Playgroud)
问题:
您正在打开和关闭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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)