当前位置: 首页 > news >正文

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;
}

http://www.dtcms.com/a/478698.html

相关文章:

  • 购物网站建设费用wordpress调用python脚本
  • 基于深度学习的数字图像分类实验与分析
  • 图像视觉——颜色识别
  • 扬州网站建设哪家公司好电商运营适合女生吗
  • HTML应用指南:利用POST请求获取全国兴业银行网点位置信息
  • Excel处理控件Aspose.Cells教程:使用 Python 将 HTML 转换为 Excel
  • 菏泽做网站的公司可玩儿小程序可以加盟么
  • 阿里云发布《AI 原生应用架构白皮书》
  • 如何在百度上注册自己的网站做网站运营有提成吗
  • 分布式数据库架构:从分库分表到NewSQL实战
  • Java的双重检查锁机制(DCL)与懒加载的单例模式
  • Qt代码-QVector向量数组的增删改查插入统计复制
  • 深圳建设门户网站博客wordpress
  • 免费做网站的好不好大理悦花轩客栈在哪些网站做推广
  • 语义与认知中的循环解释悖论及其对人工智能自然语言处理深层语义分析的影响与启示
  • 购物类网站百度关键词搜索排名
  • 微信公众号的跳转网站怎么做外贸网站要先备案吗
  • 【VSCode+WSL】开发环境随身携带:我的VSCode+cpolar远程工作站实战
  • 长沙做最好网站东营建设信息网的网址
  • Kubernetes Pod 全面详解(基础 + 进阶)
  • JAVA算法练习题day40
  • 电子电气架构 --- 车载多系统架构
  • JVM 垃圾回收算法
  • 宁波企业如何建网站网站 提示危险
  • 嵌入式开发--STM32H7系列的硬件SPI的读写函数问题
  • printk 使用技巧
  • 深度学习入门(六)——模块、正则化与工程调优全解析
  • python高级05——HTTP协议和静态服务器
  • 现在网站一般做多大的南沙网站建设哪家好
  • 使用Mathematica做Lorenz系统的稳定性分析