从文本文件中读取对象
Reading objects from text file
我正在尝试从文本文件属性中读取:char* 和 int 并创建类 B 的对象。
B * p=new B[3];
for(int i=0;i<3;i++)
{
p[i]=B("John",300);
}
ofstream file("example.txt");
for(int i=0;i<3;i++)
{
file<<p[i].getName()<<" "<<p[i].GetValue()<<endl;
}
file.close();
//saved succesfully
ifstream file2("example.txt");
B *q=new B[3];
char* temp;
int time1;
for(int i=0;i<3;i++)
{
file2>>temp>>time1;
char*name1=new char[strlen(temp)+1];
strcpy(name1,temp); //here name1 is red correctly
q[i]=B(name1,time1); //
}
file2.close();
3个对象的保存成功,我已经检查了文件。但是,当我从中读取 3 个对象时,第一个对象被正确创建,但对于其他对象,我传递的 char* 属性被初始化为 ",",第二个参数 int 也是正确的。为什么第一个对象创建成功,而其他对象没有?
>file2 >> temp
无效,因为temp
是一个未初始化的指针。此operator>>
需要一个预分配的缓冲区。
我建议使用更少的"星号"(理想情况下为零(和更多的标准容器,即 在这种情况下std::vector
和std::string
。这也将解决您的内存泄漏...
好的,如果不能,请实现您自己的功能受限版本的std::string
。其他任何事情都违反了单一责任原则,这C++不好。
如果您不想走那么远,一个简单的解决方法是将temp
设置为一个实际的数组,其大小为您希望文件中的名称的最大字符数。
最后,考虑一下是否可以制作B::name
char const*
,因此。
相关文章:
- 我可以读取静态对象中的文件.txt吗?C++
- 如何从文件中读取指向对象的指针?
- 读取互斥对象范围之外的volatile变量,而不是std::atomic
- 用rapidjson读取子对象向量
- 如何在C++中读取 HDF5 对象引用
- 尝试从文本文件读取到对象数组
- 如何使用 QDataStream 从 QTcpSocket 读取类对象?
- 在 c++ 中从数据文件中读取值对象
- 无法在C++中对从文件中读取的对象进行排序
- C nonlohmann json读取子对象
- 使用getline()从文本文件中读取行,然后将push_back读取到对象的向量中
- 从文件读取到对象
- 从文件c++中读取类对象
- C++:如何从文件读取到对象向量
- 从读取到对象指针数组的文件获取段错误
- 如何从文件中读取类对象的矢量
- C++ - 如何编写和读取包含对象的结构?(写入和读取二进制文件)
- 使用指向成员的指针读取 cons 对象的字段的值
- 使用 boost::asio::read_async 读取 Protobuf 对象
- GMtime 不适用于使用重载运算符读取的对象