从文本文件中读取对象

Reading objects from text file

本文关键字:读取 取对象 文件 文本      更新时间:2023-10-16

我正在尝试从文本文件属性中读取: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::vectorstd::string。这也将解决您的内存泄漏...

好的,如果不能,请实现您自己的功能受限版本的std::string。其他任何事情都违反了单一责任原则,这C++不好。

如果您不想走那么远,一个简单的解决方法是将temp设置为一个实际的数组,其大小为您希望文件中的名称的最大字符数。


最后,考虑一下是否可以制作B::namechar const*,因此。