写一个C++代码,要有三个文件,要求如下:将学生信息写入文本文件。一个学生的信息包括姓名和成绩,这些信息分别写入文件。要求:(1)学生的信息用一个Student类的对象表示,包含string firstName、char mi、string lastName、int score。 (2)创建两个Student对象,将它们写入一个名为object.dat的文件,然后再从文件读出两个对象内容,利用while循环判断。 (3)程序包含三个文件:Student.h,Student.cpp(25分),BinaryObjectIO.cpp(25分)文件,第三个文件中包含一个全局函数void displayStudent(Student student)的定义。
时间: 2023-03-08 09:55:47 浏览: 85
C++文件写入的基本方法,考试也许用的上
#include<iostream>
#include<fstream>
#include<string>using namespace std;//定义Student类
class Student{
public:
string firstName;
char mi;
string lastName;
int score;
};//将Student对象写入文件
void writeStudentsToFile(Student s1, Student s2, string fileName){
ofstream outfile(fileName, ios::binary);
outfile.write((char*)&s1, sizeof(s1));
outfile.write((char*)&s2, sizeof(s2));
outfile.close();
}//从文件读取Student对象
void readStudentsFromFile(string fileName){
Student s;
ifstream infile(fileName, ios::binary);
while(infile.read((char*)&s, sizeof(s))){
cout<<"firstName:"<<s.firstName<<endl;
cout<<"mi:"<<s.mi<<endl;
cout<<"lastName:"<<s.lastName<<endl;
cout<<"score:"<<s.score<<endl;
}
infile.close();
}//全局函数:显示学生信息
void displayStudent(Student student){
cout<<"firstName:"<<student.firstName<<endl;
cout<<"mi:"<<student.mi<<endl;
cout<<"lastName:"<<student.lastName<<endl;
cout<<"score:"<<student.score<<endl;
}int main(){
Student s1, s2;
s1.firstName = "John";
s1.mi = 'D';
s1.lastName = "Doe";
s1.score = 80; s2.firstName = "Jane";
s2.mi = 'F';
s2.lastName = "Smith";
s2.score = 90; writeStudentsToFile(s1, s2, "object.dat");
readStudentsFromFile("object.dat");
return 0;
}
阅读全文