从文件 c++ 读取对象
Read objects from file c++
我想从文件中读取 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*
相关文章:
- 如何在C++中从文件中读取/写入多个对象
- 使用对象文件读取三角形数据网格
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 我可以读取静态对象中的文件.txt吗?C++
- 从对象C++中的文件读取内容时出现分段错误
- 如何从文件中读取指向对象的指针?
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组
- 从一个文件中读取多个序列化对象
- 读取互斥对象范围之外的volatile变量,而不是std::atomic
- 用rapidjson读取子对象向量
- 使用 OpengGLES2(角度)从帧缓冲区对象读取
- C++两次从文件保存对象读取多重继承
- 通过 ifstream 对象读取C++中的文件
- 将C 对象读取到随机访问文件中
- 使用 C++ 将对象读取和写入二进制文件
- C++在尝试编写对象读取器时,在尝试从一个向量获取数据时出错
- Boost.python 将对象拉取到本地范围内以进行读取访问
- 为什么这个ifstream无法将平面对象读取到内存中
- 如何在C++中从istream对象读取时检测空行
- C++使用fstream对象读取和写入文本文件时出现问题