C++ 使用ifstream和ofstream儲存包含string型別的類時出現程式中斷
阿新 • • 發佈:2019-01-06
閒話少說,先看一段簡單的程式碼
#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