• c++day7


    1.XMIND

    2.

    试编程:

    封装一个学生的类,定义一个学生这样类的vector容器, 里面存放学生对象(至少3个)

    再把该容器中的对象,保存到文件中。

    再把这些学生从文件中读取出来,放入另一个容器中并且遍历输出该容器里的学生。

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. //封装 学生 类
    6. class Student
    7. {
    8. public:
    9. string name;
    10. int age;
    11. string speak;
    12. public:
    13. Student(){}
    14. Student(string name, int age, string speak):name(name),age(age),speak(speak)
    15. {}
    16. };
    17. int main()
    18. {
    19. //创建三个类对象
    20. Student s1("北原春希",18,"你们都是我的翅膀");
    21. Student s2("小木曾雪菜",17,"为什么会变成这样呢……第一次有了喜欢的人。有了能做一辈子朋友的人。两件快乐事情重合在一起。而这两份快乐,又给我带来更多的快乐。得到的,本该是像梦境一般幸福的时间……但是,为什么,会变成这样呢……");
    22. Student s3("冬马和纱",17,"是我,是我先,明明都是我先来的……接吻也好,拥抱也好,还是喜欢上那家伙也好");
    23. //创建一个类的容器,存储类对象
    24. vector v;
    25. v.push_back(s1);
    26. v.push_back(s2);
    27. v.push_back(s3);
    28. //把容器中的对象保存在文件中
    29. ofstream ofs;
    30. ofs.open("D:/QTfile/Student.txt",ios::out);
    31. vector::iterator i;
    32. for(i=v.begin();i!=v.end();i++)
    33. {
    34. ofs << i->name << " " << i->age << ":"<< i->speak <
    35. }
    36. ofs.close();
    37. //文件中读取出来,存储在新容器中
    38. vector new_v;
    39. ifstream ifs;
    40. ifs.open("D:/QTfile/Student.txt",ios::in);
    41. string name;
    42. int age;
    43. string speak;
    44. while(ifs >> name >> age >> speak)
    45. {
    46. new_v.push_back(Student(name,age,speak));
    47. }
    48. ifs.close();
    49. //遍历新容器中的对象
    50. vector::iterator new_i;
    51. for(new_i=new_v.begin();new_i!=new_v.end();new_i++)
    52. {
    53. cout<< new_i->name << " " << new_i->age << " " << new_i->speak << endl << endl;
    54. }
    55. return 0;
    56. }

  • 相关阅读:
    leetcode每天5题-Day50
    vvic API接口接入说明:解锁新一代数据可视化的无限可能
    长安链GO语言智能合约环境搭建及使用
    数据结构名词解释详细总结
    golang解析excel、csv编码格式
    C++:程序运行的开始和结束
    MybatisPlus通用枚举
    Android笔记
    Vue将Element Plus 进行自定义封装
    python astra相机驱动问题
  • 原文地址:https://blog.csdn.net/m0_72133977/article/details/133814901