基本上,這個問題已經在標題中描述了。當第一次啟動程式時(意味著新的檔案在那時被創建),它作業得很好,而且沒有崩潰,但當第二次嘗試時(意味著檔案已經在那里),它崩潰了。
問題是:為什么它會崩潰,我怎樣才能防止這種情況發生?
以下是代碼:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
class TStudent
{
public:
string Name, Surname;
int 年齡。
TStudent(string name, string surname, int age)
{
名字 = 名字。
Surname = surname;
年齡 = 年齡。
cout <<"
"。
}
string toString() const
{
return Name " ; " Surname " ; " to_string(年齡)。
}
int aux1 = sizeof(姓名),aux2 = sizeof(姓氏)。
};
class Tegistru
{
public:
string name, surname;
int age。
向量 <TStudent> 學生。
TRegistru(const TStudent &other)
{
this->name = other.Name。
this-> surname = other.Surname;
this->age = other.Age。
students.push_back(other)。
}
void adauga(const TStudent& student)
{
students.push_back(student)。
}
void salveaza(string file_name)//創建檔案并儲存資料
{
ofstream file1;
file1.open(file_name, ios::app)。
file1.write((char*)&students, sizeof(students)) 。
file1.close()。
cout<<"
檔案已保存并成功關閉。
"<<endl。
}
void sterge()
{
students.clear()。
}
void incarca(string file_name)//span>打開檔案并讀取資料
{
ifstream file2。
file2.open(file_name, ios::in)。
if(!file2)
{
cout<<"打開檔案時有錯誤。"。
}
else; }
{
cout<<"檔案打開成功。
"<<endl。
}
file2.seekg(0)。
file2.read((char*)&students, sizeof(students))。
}
void afiseaza()//printing the data
{
for(auto student : students)
{
cout << student.Name << endl ;
cout << student.Surname << endl;
cout << student.Age << endl;
cout <<"
"。
}
}
string toString() const
{
string ret{}。
for(const auto& students : students)
{
ret = student.toString() "
"。
}
return ret;
}
};
int main()
{
TStudent student1("Simion", "Neculae", 21)。
TStudent student2("Elena", "Oprea", 21)。
TRegistru registru(student1)。
registru.adauga(學生2)。
registru.salveaza("data.bin");//創建檔案并儲存資料。
registru.sterge()。
registru.incarca("data.bin");//打開檔案和讀取資料。
registru.afiseaza();//printing the data。
return 0。
}
uj5u.com熱心網友回復:
在第二次閱讀你的代碼后,我意識到你試圖讀寫一個向量的方式是完全錯誤的:
vector <TStudent> students。
...
ifstream file2;
file2.open(file_name, ios::in)。
file2.seekg(0)。
file2.read((char*)&students, sizeof(students)); // WRONG!!!
向量確實以連續的方式存盤其資料,但是向量的地址是不是資料的地址。正確的方法是將向量的每個元素序列化到檔案中,然后反序列化每個元素并將其推入向量中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328099.html
標籤:
