11-6

定义一个dog类,包含体重和年龄两个成员变量及相应的成员函数,声明一个实例dog1,体重为5,年龄为10,使用I/O流把dog1的状态写入磁盘文件,再声明另一个实例dog2,通过读文件把dog1的状态赋给dog2。分别使用文本方式和二进制方式操作文件,看看结果有何不同;再看看磁盘文件的ASCII码有何不同。

 1 #include <iostream>
 2 #include <string>
 3 #include<string.h>
 4 #include <fstream>
 5 using namespace std;
 6 
 7 class Dog{
 8     int age;
 9     int weight;
10 public:
11     Dog():age(0),weight(0){}
12     Dog(int age, int weight):age(age), weight(weight){}
13     void show(){cout<<"age:"<<age<<endl<<"weight:"<<weight<<endl; }
14     ~Dog(){}
15 };
16 
17 int main(){
18     Dog dog1(10, 5);
19     //ofstream file1("dog.txt");
20     ofstream file1("dog.txt",ios::binary);
21     file1.write((char*)&dog1,sizeof(dog1));
22     file1.close();
23     
24     Dog dog2;
25     //ifstream file2("dog.txt");
26     ifstream file2("dog.txt", ios::binary);
27     file2.read((char*)&dog2, sizeof(dog2));
28     file2.close();
29     dog2.show();
30     return 0;
31 }

 

posted @ 2023-03-28 19:39  nlkdfgnvfdkl  阅读(56)  评论(0)    收藏  举报