周二

问题描述:

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

设计思路:
问题描述就是思路

程序流程图:

定义Dog类->dog1(10,5)->写入文件->读取文件->写入dog2->结束

代码实现:

文件方式:

#include<iostream>
#include<fstream>
using namespace std;
class Dog{
public:int age,weight;
    Dog(int a,int b):age(a),weight(b){}
    Dog(){};
};
Dog dog1(10,5);
fstream fs;
int a,b;
int main(){
    fs.open("D:\\66\\dog1.txt",ios::out);
    fs<<dog1.age<<" "<<dog1.weight;
    fs.close();
    fs.open("D:\\66\\dog1.txt",ios::in);
    fs>>a;fs>>b;
    Dog dog2(a,b);
    cout<<dog2.age<<" "<<dog2.weight<<endl;
    fs.close();
    return 0;
}

二进制方式:

#include<iostream>
#include<fstream>
using namespace std;
class Dog{
public:int age,weight;
    Dog(int a,int b):age(a),weight(b){}
    Dog(){}
};
int main(){
    Dog dog1(10,5);
    fstream fs;
    fs.open("D:\\66\\Dog1.txt",ios::out|ios::binary);
    fs.write((char *)&dog1,sizeof(dog1));
    fs.close();
    Dog dog2;
    fs.open("D:\\66\\Dog1.txt",ios::in|ios::binary);
    while(fs.read((char *)&dog2,sizeof(dog2)));
    cout<<dog2.age<<" "<<dog2.weight;
    return 0;
}

posted @ 2023-05-16 15:53  菜鸟de博客  阅读(75)  评论(0)    收藏  举报