【发布时间】:2020-11-17 08:19:54
【问题描述】:
我创建了要存储在二进制文件中的学生数据,但该文件已完全损坏。
我做错了什么?
记事本中存储的文本文件没有问题。
现在启动程序后进入后,只写这样的:
& Ô LC_CTYPE = C; LC_M0 & Ô RIC = C; LC_TIME = C
有人可以帮我解决这个问题吗?祝你有美好的一天:)
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
struct Student{
string imie;
string nazwisko;
int nrAlbumu;
int wiek;
float srOcen;
} dane;
int main(){
Student dane;
cout << "Podaj imie:" << endl;
cin >> dane.imie;
cout << "Podaj nazwisko:" << endl;
cin >> dane.nazwisko;
cout << "Podaj nrAlbumu:" << endl;
cin >> dane.nrAlbumu;
cout << "Podaj wiek:" << endl;
cin >> dane.wiek;
cout << "Podaj srednia ocen:" << endl;
cin >> dane.srOcen;
cout << "Student " << dane.imie <<" "<< dane.nazwisko << " o numerze albumu: " << dane.nrAlbumu << " ma lat " << dane.wiek << " ma srednia ocen rowna: " << dane.srOcen << endl;
//-------writing to the file starts here-------------------------
ofstream ofs("dane.bin", ios::binary);
Student* student = new Student;
student->imie;
student->nazwisko;
student->nrAlbumu;
student->wiek;
student->srOcen;
ofs.write((char*)(student), sizeof(Student));
ofs.close();
delete student;
//-------------reading starts here ---------------------------
ifstream ifs("dane.bin", ios::binary);
char* temp = new char[sizeof(Student)];
ifs.read(temp, sizeof(Student));
Student* student2 = (Student*)(temp);
cout << "Student " << dane.imie <<" "<< dane.nazwisko << " o numerze albumu: " << dane.nrAlbumu << " oraz ma lat " << dane.wiek << " ma srednia ocen rowna: " << dane.srOcen <<" Potwierdzenie do zapisu i odczytu!" << endl;
delete student;
return 0;
}
【问题讨论】:
-
ofs.write((char*)(student), sizeof(Student));-- 这永远行不通。不能轻易复制的类型不能像这样写入二进制文件。您需要序列化对象,而不仅仅是将原始字节写入二进制文件。 -
我应该从什么意义上理解?微不足道的可复制?我不明白
-
Student对象包含std::string。这是一个不可简单复制的对象,因此Student类不可简单复制。如果你想要更多的证据,sizeof做什么?它返回什么值?sizeof是编译时值。现在假设std::string有一个 1000 个字符的size()。sizeof不知道std::string将有多少个字符在运行时。因此,整条线没有意义,也不会工作。如果你std::cout << sizeof(Student);你得到什么价值?我敢打赌它不是 1000。