5.18打卡

一、实验内容

定义一个Dog类,包括体重和年龄两个数据成员及其成员函数,声明一个实例dog1,体重5,年龄10,使用I/O流把dog1的状态写入磁盘文件。再声明一个实例dog2,通过读取文件dog1的状态赋给dog2。分别用文本方式和二进制方式操作文件。

二、实验代码

复制代码
#include<bits/stdc++.h>
using namespace std;
class Dog
{
public:
 double weight;
 int age;
 } ;
 
 struct ConfigManager
 {
  public:
   ConfigManager(const char* configfile = "bitsserver.config")
    :_configfile(configfile)
    {
    }
  void WriteBin(const Dog& info)
  {
   ofstream ofs(_configfile, ifstream::out | ifstream::binary);
   ofs.write((const char*)&info, sizeof(Dog));
   ofs.close();
  }
  void ReadBin(Dog& info)
  {
   ifstream ifs(_configfile, ifstream::in | ifstream::binary);
   ifs.read((char*)&info, sizeof(Dog));
   ifs.close();
  }
  
  void WriteText(const Dog& info)
  {
   ofstream ofs(_configfile);
   ofs << info.age << endl;
   ofs << info.weight << endl;
   ofs.close();
  }
  void ReadText(Dog& info)
  {
   ifstream ifs(_configfile);
   ifs >> info.age;
   ifs >> info.weight;
   ifs.close();
  }
 private:
  string _configfile; 
 
 };
 int main()
 {
  ConfigManager cfgMgr;
  Dog dog1;
  Dog dog2;
  dog1.weight = 5;
  dog1.age = 10;
  //文本 
  cfgMgr.WriteText(dog1);
  cfgMgr.ReadText(dog2);
  cout << dog2.age << endl;
  cout << dog2.weight << endl;
  //二进制 
  cfgMgr.WriteBin(dog1);
  cfgMgr.ReadBin(dog2);
  cout << dog2.age << endl;
  cout << dog2.weight << endl; 
  
  return 0; 
 }
复制代码

三、测试截图

 

 

posted @   yblll  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示