关于二进制文件的输入问题
假设编写一个程序,将创建2个student类对象,写入了一个二进制文件(文件名为object.dat),然后再读取这个文件中的Student对象程序如下(Student类的实现省略了):
#include <iostream>
#include <fstream>
#include "Student.h"
using namespace std;
void displayStudent(Student student)//该函数显示学生对象的名字和分数
{
cout << student.getFirstName() << " ";
cout << student.getMi() << " ";
cout << student.getLastName() << " ";
cout << student.getScore() << endl;
}
int main()
{
fstream binaryio;
binaryio.open("object.dat", ios::out | ios::binary);
Student student1("John", 'T', "Smith", 90);
Student student2("Eric", 'K', "Jones", 86);
binaryio.write(reinterpret_cast<char *>(&student1), sizeof(Student));
binaryio.write(reinterpret_cast<char *>(&student2), sizeof(Student));
binaryio.close();
binaryio.open("object.dat", ios::in | ios::binary | ios::eofbit);
Student newStudent;
while (!binaryio.eof())
{
binaryio.read(reinterpret_cast<char*>(&newStudent), sizeof(Student));
displayStudent(newStudent);}
binaryio.close();
return 0;
}
为什么输出结果显示三个学生对象,后两个重复了,如何避免这个问题呢?非常感谢