You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
2.2 KiB
67 lines
2.2 KiB
#include <iostream>
|
|
#include <fstream>
|
|
#include <string>
|
|
using std::cin, std::cout, std::string;
|
|
|
|
class Student
|
|
{
|
|
string name; // 学生姓名
|
|
int course_num; // 学生课程数
|
|
int *score; // 指向动态分配成绩数组
|
|
const char *filename; // 用来处理读写文件的名字
|
|
|
|
public:
|
|
Student(string _name, int _course_num, const char *_filename)
|
|
: name{_name}, course_num{_course_num}, filename{_filename}
|
|
{
|
|
score = new int[course_num]{};
|
|
cout << "请依次输入" << course_num << "门课的成绩:";
|
|
for (int i = 0; i < course_num; ++i)
|
|
std::cin >> score[i];
|
|
}
|
|
|
|
Student(const char *_filename) : filename{_filename}
|
|
{
|
|
std::ifstream infile(filename, std::ios::in | std::ios::binary);
|
|
if (infile)
|
|
{
|
|
int len{};
|
|
infile.read(reinterpret_cast<char *>(&len), sizeof(int));
|
|
char *buffer = new char[len + 1]{};
|
|
infile.read(buffer, len);
|
|
name = buffer;
|
|
delete[] buffer;
|
|
infile.read(reinterpret_cast<char *>(&course_num), sizeof(course_num));
|
|
score = new int[course_num]{};
|
|
infile.read(reinterpret_cast<char *>(score), course_num * sizeof(int));
|
|
infile.close();
|
|
}
|
|
}
|
|
~Student()
|
|
{
|
|
std::ofstream ofile(filename, std::ios::out | std::ios::binary);
|
|
{
|
|
int len{static_cast<int>(name.size())};
|
|
ofile.write(reinterpret_cast<char *>(&len), sizeof(len));
|
|
ofile.write(name.c_str(), len);
|
|
ofile.write(reinterpret_cast<char *>(&course_num), sizeof(course_num));
|
|
ofile.write(reinterpret_cast<char *>(score), course_num * sizeof(int));
|
|
ofile.close();
|
|
delete[] score;
|
|
}
|
|
}
|
|
friend std::ostream &operator<<(std::ostream &os, Student &s)
|
|
{
|
|
os << "姓名:" << s.name << " 成绩:";
|
|
for (int i{0}; i < s.course_num; ++i)
|
|
os << s.score[i] << '\t';
|
|
return os << '\n';
|
|
}
|
|
};
|
|
|
|
int main()
|
|
{
|
|
Student s1{"TOM", 5, "s1.dat"};
|
|
// Student s1{"s1.dat"}; 这句话和上面的语句分两次运行即可
|
|
cout << s1;
|
|
} |