我有使用 visual studio 读取名为“student.dat”的文件的基本文件处理代码。
输出读取文件并在控制台中显示结果,但 visual studio 弹出对话框为
代码:
#include<iostream>
#include<fstream>
#include<conio.h>
#include<string>
using namespace std;
class student
{
int admno;
// char name[20];
string name;
public:
void getdata()
{
cout<<"\n\nEnter The Name of The Student ";
//gets(name);
cin>>name;
getch();
cout<<"\nEnter The admission no. ";
cin>>admno;
// getch();
}
void showdata()
{
cout<<"\nAdmission no. : "<<admno;
cout<<"\nStudent Name : ";
cout<<name;
//puts(name);
}
int retadmno()
{
return admno;
}
};
int main()
{
student obj;
ifstream fp1;
fp1.open("student.dat",ios::binary);
while(fp1.read((char*)&obj,sizeof(obj)))
{
obj.showdata();
}
fp1.close();
return 0;
}
最佳答案
您只能将原始数据加载到某些 POD 对象。这一行是一个错误:
fp1.read( (char*)&obj,sizeof(obj) );
因为 student
包含 std::string
。 std::string
包含指向内存块的指针,该内存块在对象被销毁后变得无效且完全无用。这意味着您加载到 std::string
的数据只是垃圾。
我会考虑对象序列化。 Boost serialization是一个很好的开始方式。
关于c++ - C++ 中的文件处理会导致 .exe 停止工作错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22528403/