I'm trying to write a C++ code that read from a text file, write all the contents into a binary file, and read a record from the binary file.To hold records, I created a Student class that one of its attribute is enum type.I read from text file successfully, I write the Student records successfully (I check it while debugging), but I have a problem with reading one Nth record from the binary file.Although all attribute are taken successfully, the last attribute whic is enum type is not changed and seems as default even for all records.Although no error exists in the VS 2017, with debugging I recognize that the problem is at binaryRead and readRecord parts (The data in "this" shows the enum attribute as NONE.Also sizeOfOneStudentRecord in seekg, read, readRecord, binaryRead etc. can be not true. I need help friends. The code is given below. I will aprreciate your help.
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;}