C++ 使用ifstream和ofstream存储包含string类型的类时出现程序中断

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xianyunxiaohe/article/details/85909519

闲话少说,先看一段简单的代码

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#pragma warning(disable:4996)
using namespace std;
class teacher
{
public:
    teacher()
    {

    }
    teacher(string  name, int age)
    {
        this->name = name;
        
        this->age = age;
    }
    string GetName()
    {
        return name;
    }
    string SetName(string name)
    {
        this->name = name;
    }
    int GetAge()
    {
        return age;
    }
    ~teacher()
    {

    }
    void Print()
    {
        cout << this->name << "  " << this->age;
    }
private:
    
    string name;
    int age;
};


int main()
{
    teacher t1("zhangsan",20);
    teacher t2("李四",40);
    ofstream fin("test1.txt", ios::binary);
    fin.write((char *)&t1, sizeof(teacher));
    fin.write((char *)&t2, sizeof(teacher));
    
    fin.close();

    teacher tmp;
   
    ifstream fout("test1.txt", ios::binary);    
    fout.read((char *)&tmp, sizeof(teacher));
    tmp.Print();
    cout << endl;
    fout.read((char *)&tmp, sizeof(teacher));
    tmp.Print();
    cout << "string:"<<sizeof(string) << endl;     
    fout.close();
    return 0;

}

当使用以上代码的方法时,虽然vs2013运行时不会报错,但是当你单步调试的时候,到最后析构teacher这个类的时候,会有程序中断。原因是因为string类型导致的,本人使用以下代码就不会有这个问题,代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#pragma warning(disable:4996)
using namespace std;
class teacher
{
public:
	teacher()
	{

	}
	teacher(char* name, int age)
	{
		this->name = name;
		//strcpy(this->name, name);
		this->age = age;
	}
	string GetName()
	{
		return name;
	}
	string SetName(string name)
	{
		this->name = name;
	}
	int GetAge()
	{
		return age;
	}
	~teacher()
	{

	}
	void Print()
	{
		cout << this->name << "  " << this->age;
	}
private:
	//char name[50];
	string name;
	int age;
};


int main()
{
	teacher t1("zhangsan",20);
	teacher t2("李四",40);
	ofstream fin("test1.txt", ios::binary);
//	fin.write((char *)&t1, sizeof(teacher));
//	fin.write((char *)&t2, sizeof(teacher));
	fin << t1.GetName() << endl;
	fin << t1.GetAge() << endl;
	fin.close();

	teacher tmp;
	char name_tt[30];
	string name_tmp;
	ifstream fout("test1.txt", ios::binary);
	/*
	fout.read((char *)&tmp, sizeof(teacher));
	tmp.Print();
	cout << endl;
	fout.read((char *)&tmp, sizeof(teacher));
	tmp.Print();
	cout << "string:"<<sizeof(string) << endl;
	*/
	fout.getline(name_tt, 30);
	cout << name_tt << endl;
	fout.close();
	return 0;

}

至于为什么会出现这种问题,本人也不晓得,网上有人说是string的存储不是连续,但是这和string的析构有什么关系?欢迎大家讨论。

在此谢谢大家。。。

参考文献:

https://blog.csdn.net/sq1652827791/article/details/48176597

https://stackoverflow.com/questions/10335714/c-iostream-binary-read-and-write-issues

猜你喜欢

转载自blog.csdn.net/xianyunxiaohe/article/details/85909519