一.问题描述
定义一个dog类,包含体重和年龄两个成员变量及相应的成员函数,声明一个实例dog1,体重为5,年龄为10,使用I/O流把dog1的状态写入磁盘文件,再声明另一个实例dog2,通过读文件把dog1的状态赋给dog2。分别使用文本方式和二进制方式操作文件,看看结果有何不同;再看看磁盘文件的ASCII码有何不同。
三.流程图
四.伪代码
1
五.代码实现
1#include<iostream>
#include<fstream>
using namespace std;
class Dog {
private:
int weight;
long numberdayalive;
public:
Dog(int weight, long days) :weight(weight), numberdayalive(days) {}
~Dog() {}
int getweight() const {
return weight;
}
void setweight() {
cin >> weight;
}
int getnumberdayalive() const {
return numberdayalive;
}
void setnumberdayalive() {
cin >> numberdayalive;
}
};
int main() {
char filename[80];
cout << "Please enter file name:";
cin >> filename;
ofstream fout(filename);
if (!fout) {
cout << "unable to open " << filename << " for writing." << endl;
return { 1 };
}
Dog dog1(5, 10);
fout.write((char*)&dog1, sizeof dog1);
fout.close();
ifstream fin(filename);
if (!fin) {
cout << "unable to open " << filename << " for reading." << endl;
return { 1 };
}
Dog dog2(2, 10);
cout << "dog2 weight:" << dog2.getweight() << endl;
cout << "dog2 days:" << dog2.getnumberdayalive() << endl;
fin.read((char*)&dog2, sizeof dog2);
cout << "dog2 weight:" << dog2.getweight() << endl;
cout << "dog2 days:" << dog2.getnumberdayalive() << endl;
fin.close();
return 0;
}
标签:numberdayalive,21.4,weight,int,每日,Dog,filename,打卡,dog1 From: https://www.cnblogs.com/leapssisbird/p/17392527.html