0

我正在尝试编写从文本文件读取的 C++ 代码,将所有内容写入二进制文件,并从二进制文件中读取记录。为了保存记录,我创建了一个 Student 类,其属性之一是枚举类型。我成功地从文本文件中读取,我成功地写入学生记录(我在调试时检查它),但是我从二进制文件中读取第 N 条记录时遇到问题。虽然所有属性都成功获取,但最后一个属性是枚举类型没有更改,即使对于所有记录也似乎是默认值。尽管 VS 2017 中不存在错误,但通过调试我认识到问题出在binaryReadreadRecord部分(“this”中的数据显示枚举属性为 NONE。还有sizeOfOneStudentRecordseekgreadreadRecordbinaryRead等可能不正确。我需要帮助的朋友。代码如下。我会感谢你的帮助。

enum Category { NONE = 0, Honor=1, High_Honor = 2 }; class Student { private: string name; double weight; int age; Category degree; public: Student(); Student(string _name, double _weight, int _age, Category _degree); Student* txtRead(ifstream& myFile); size_t sizeOfOneStudentRecord(Student* a); void binaryWrite(fstream& myFile); void binaryRead(fstream& myFile); void readRecord(fstream& binmyFile, int order); friend ostream& operator<<(ostream& output, Student& s) { .. } }; Student::Student() { name = ""; weight = 0.0; age = 0; degree = NONE; } Student::Student(string _name, double _weight, int _age, Category _degree) { name = _name; weight = _weight; age = _age; degree = _degree; } size_t Student::sizeOfOneStudentRecord(Student* c) { return sizeof(this->name) + sizeof(this->weight) + sizeof(this->age) + sizeof(this->degree); } Student* Student::txtRead(ifstream& myFile) { ... } void Student::binaryWrite(fstream& myFile) { myFile.write((char *)this, sizeOfOneStudentRecord(this)); } void Student::binaryRead(fstream& myFile) { myFile.read((char*)this, sizeOfOneStudentRecord(this)); } void Student::readRecord(fstream& binmyFile, int order) { binmyFile.seekg((order)*sizeOfOneStudentRecord(this)); binaryRead(binmyFile); name = this->name; age = this->age; weight = this->weight; degree = this->degree; } int main() { Student *StudentArr[20]; ifstream myFile("Student.txt", ios::in); ofstream txtmyFile("newStudentFile.txt", ios::out | ios::trunc); fstream binmyFile("StudentBin.bin", ios::out | ios::in | ios::trunc | ios::binary); for (int i = 0; i < 20; i++) { StudentArr[i] = new Student(); StudentArr[i]->txtRead(myFile); txtmyFile << *StudentArr[i]; StudentArr[i]->binaryWrite(binmyFile); } myFile.close(); txtmyFile.close(); Student s1; s1.readRecord(binmyFile, 8); std::cout << s1 << endl; binmyFile.close(); return 0;}

4

0 回答 0