C++多文件编程完整代码:将学生信息写入文本文件。一个学生的信息包括姓名和成绩,这些信息分别写入文件。要求:(1)学生的信息用一个Student类的对象表示,包含string firstName、char mi、string lastName、int score。 (2)创建两个Student对象,将它们写入一个名为object.dat的文件,然后再从文件读出两个对象内容,利用while循环判断。 (3)程序包含三个文件:Student.h,Student.cpp(25分),
时间: 2023-03-08 20:59:16 浏览: 91
main.cpp(25分)我可以为您提供一个示例,以帮助您完成您的任务:// Student.h
#ifndef STUDENT_H
#define STUDENT_H#include <string>class Student {
private:
std::string firstName;
char mi;
std::string lastName;
int score;public:
Student(std::string firstName, char mi, std::string lastName,
int score);
std::string getFirstName() const;
char getMi() const;
std::string getLastName() const;
int getScore() const;
};#endif // STUDENT_H// Student.cpp
#include "Student.h"Student::Student(std::string firstName, char mi, std::string lastName,
int score)
: firstName(firstName), mi(mi), lastName(lastName), score(score)
{
}std::string Student::getFirstName() const {
return firstName;
}char Student::getMi() const {
return mi;
}std::string Student::getLastName() const {
return lastName;
}int Student::getScore() const {
return score;
}// main.cpp
#include <fstream>
#include <iostream>
#include "Student.h"int main() {
Student student1("John", 'A', "Doe", 95);
Student student2("Jane", 'B', "Smith", 80); std::ofstream fout("object.dat", std::ios::out | std::ios::binary);
if (!fout.good()) {
std::cerr << "Cannot open file!" << std::endl;
return 1;
} fout.write(reinterpret_cast<char*>(&student1), sizeof(Student));
fout.write(reinterpret_cast<char*>(&student2), sizeof(Student));
fout.close(); Student student;
std::ifstream fin("object.dat", std::ios::in | std::ios::binary);
if (!fin.good()) {
std::cerr << "Cannot open file!" << std::endl;
return 1;
} while (fin.read(reinterpret_cast<char*>(&student), sizeof(Student))) {
std::cout << student.getFirstName() << " " << student.getMi()
<< " " << student.getLastName() << " " << student.getScore()
<< std::endl;
} fin.close(); return 0;
}
阅读全文