定义一个学生类Student,包含学生姓名、学号以及成绩数据成员;重载输出流运算符operator<<,用于输出上述三个成员;在主函数main函数中建立若干Student成员,将这些对象保存到数据文件中;最后读取并显示文件内容
时间: 2024-03-10 10:49:25 浏览: 30
好的,下面是实现代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Student {
private:
string name; // 学生姓名
string id; // 学号
double score; // 成绩
public:
// 构造函数
Student(string n, string i, double s) : name(n), id(i), score(s) {}
// 重载输出流运算符
friend ostream& operator<<(ostream& os, const Student& s) {
os << "姓名:" << s.name << ",学号:" << s.id << ",成绩:" << s.score << endl;
return os;
}
};
int main() {
Student s1("张三", "20210001", 89.5);
Student s2("李四", "20210002", 92.0);
Student s3("王五", "20210003", 85.5);
// 保存到数据文件
ofstream outfile("students.txt");
outfile << s1 << s2 << s3;
outfile.close();
// 读取并显示文件内容
ifstream infile("students.txt");
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
return 0;
}
```
运行结果:
```
姓名:张三,学号:20210001,成绩:89.5
姓名:李四,学号:20210002,成绩:92
姓名:王五,学号:20210003,成绩:85.5
```