定义一个学生类 Student,包含学生姓名、学号以及成绩数据成员;重载输出流运算符 operator<<,用于输出上述三个成员:在 main 函数中建立若干 Student 对象,将这些对象保存到数据文件中,最后读取并显示文件内容
时间: 2024-02-25 20:53:12 浏览: 26
好的,我来为您编写C++代码实现这个需求:
```cpp
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class Student {
public:
Student(string name, int id, double score) {
this->name = name;
this->id = id;
this->score = score;
}
friend ostream& operator<<(ostream& os, const Student& stu) {
os << "姓名:" << stu.name << ",学号:" << stu.id << ",成绩:" << stu.score << endl;
return os;
}
private:
string name;
int id;
double score;
};
int main() {
// 建立若干 Student 对象
vector<Student> students;
students.push_back(Student("张三", 101, 85.5));
students.push_back(Student("李四", 102, 90.0));
students.push_back(Student("王五", 103, 92.5));
// 将这些对象保存到数据文件中
ofstream outfile("students.txt");
if (outfile.is_open()) {
for (int i = 0; i < students.size(); i++) {
outfile << students[i];
}
outfile.close();
} else {
cout << "文件打开失败!" << endl;
return -1;
}
// 读取并显示文件内容
ifstream infile("students.txt");
if (infile.is_open()) {
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
} else {
cout << "文件打开失败!" << endl;
return -1;
}
return 0;
}
```
运行结果如下:
```
姓名:张三,学号:101,成绩:85.5
姓名:李四,学号:102,成绩:90
姓名:王五,学号:103,成绩:92.5
```
希望能够帮助到您!