【发布时间】:2020-11-26 16:05:59
【问题描述】:
我正在学习 c++,但在文件处理方面遇到了麻烦。我正在编写一个代码作为作业,我必须将对象写入文件,然后一次将这些对象作为数组从文件中读取。这是我的代码:
#include <iostream>
#include <fstream>
using namespace std;
class Records{
char* name;
int roll;
public:
Records()
{
name = new char[20];
}
void setData()
{
cout<<"Enter name: "<<endl;
cin>>name;
cout<<"Enter roll"<<endl;
cin>>roll;
}
char* getname()
{
return name;
}
int getRoll()
{
return roll;
}
void operator = (Records& no)
{
name = no.name;
roll = no.roll;
}
};
int main()
{
int i =0 ;
Records rec;
rec.setData();
Records::increase();
ofstream fout;
fout.open("file.txt", ios::app);
fout.write((char*)&rec, sizeof(rec));
fout.close();
Records* results = new Records[20];
Records rec1;
ifstream fin;
fin.open("file.txt", ios::in);
while(!fin.eof())
{
fin.read((char*)&rec1, sizeof(rec1));
results[i] = rec1;
i++;
}
fin.close();
cout<<results[0].getRoll();
return 0;
}
所以基本上,我创建了一个 Records 类并将其对象存储在一个文件中。这很好,但我在从文件中获取数据时遇到了问题。它没有显示任何内容或有时显示垃圾值。任何人有更好的想法请帮助我。 提前致谢!
【问题讨论】:
-
你必须使用原始指针吗?为什么不使用
std::string?由于char* name,您的类非常不安全,并且它泄漏内存,因为您没有delete[]指针。阅读rule of 3/5/0。另请阅读:Why isiostream::eof()inside a loop condition (i.e.while (!stream.eof())) considered wrong? -
您不能将指针存储在文件中并在以后使用它们。你需要某种序列化。
-
你做的水平比较低,没必要那么低。如果您只想将字符串和每行的数字写入文本文件,使用
ofstreamsoperator<<会简单得多
标签: c++ file-handling