c++ 标准模板库练习
题目:封装一个学生的类,定义一个学生这样类的vector容器, 里面存放学生对象(至少3个)
再把该容器中的对象,保存到文件中。
再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容器里的学生
#include <iostream>
#include <vector>
#include <fstream>
#include <string>using namespace std;// 学生类
class Student {
public:string name;int age;int id;// 默认构造函数Student() : name(""), age(0), id(0) {}// 带参数构造函数Student(string n, int a, int i) : name(n), age(a), id(i) {}// 显示学生信息void display() const {cout << "学号: " << id << ", 姓名: " << name << ", 年龄: " << age << endl;}
};int main() {// 创建学生vector容器并添加学生vector<Student> students;students.push_back(Student("张三", 20, 1001));students.push_back(Student("李四", 21, 1002));students.push_back(Student("王五", 19, 1003));// 将学生信息保存到文件ofstream outFile("students.txt");if (outFile.is_open()) {for (const auto& student : students) {outFile << student.id << " " << student.name << " " << student.age << endl;}outFile.close();cout << "学生信息已保存到文件" << endl;} else {cout << "无法打开文件进行写入" << endl;return -1;}// 从文件读取学生信息到另一个容器vector<Student> readStudents;ifstream inFile("students.txt");if (inFile.is_open()) {int id, age;string name;while (inFile >> id >> name >> age) {readStudents.push_back(Student(name, age, id));}inFile.close();cout << "学生信息已从文件读取" << endl;} else {cout << "无法打开文件进行读取" << endl;return -1;}// 遍历输出读取的学生信息cout << "\n从文件读取的学生信息:" << endl;for (const auto& student : readStudents) {student.display();}return 0;
}