c++ - C++ 中的文件处理会导致 .exe 停止工作错误

标签 c++ file

我有使用 visual studio 读取名为“student.dat”的文件的基本文件处理代码。

输出读取文件并在控制台中显示结果,但 visual studio 弹出对话框为

enter image description here

代码:

#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::stringstd::string 包含指向内存块的指针,该内存块在对象被销毁后变得无效且完全无用。这意味着您加载到 std::string 的数据只是垃圾。

我会考虑对象序列化。 Boost serialization是一个很好的开始方式。

关于c++ - C++ 中的文件处理会导致 .exe 停止工作错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22528403/

相关文章:

c++ - 无法使用 std::conditional 为函数参数推断模板参数 'T'

java - 将 pdf/excel 文件动态传输到 Flex UI 应用程序

java - 输入不匹配异常?我还是想不通

C++:创建可以访问基类私有(private)变量的派生类?

c++ - 将配置从 Debug 更改为 Release 时出现链接错误

c++ - 在 Linux 中是否有将 wstring 或 wchar_t* 转换为 UTF-8 的内置函数?

c++ - 潜在的错误 openGL

c - 从文件中读取单词并将它们放入数组中

C++ fstream 如何从文本文件中读取特定行

c - 当/dev/ttyUSB* 出现时打开它