PTA练习题

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

复制代码
 1 #include <iostream>
 2 #include <fstream>
 3 using namespace std;
 4 class  Dog{
 5     public:
 6         int ages;
 7         int weight;
 8         Dog(int w,int a)
 9         {
10             weight=w;
11             ages=a;
12         }
13         Dog(){
14         }
15 };
16 int main()
17 {
18     Dog dog1(5,10);
19     fstream file1;
20     file1.open("text.txt",ios::out);
21     file1<<dog1.weight<<endl;
22     file1<<dog1.ages<<endl;
23     file1.close();
24     ifstream file2;
25     file2.open("text.txt",ios::in);
26     if(!file2.is_open())
27     {
28         cout<<"文件打开失败"<<endl;
29         return 0;
30     }
31     Dog dog2(1,1);
32     file2>>dog2.weight>>dog2.ages;
33     cout<<dog2.weight<<endl;
34     cout<<dog2.ages<<endl;
35     file2.close();    
36 }
复制代码
复制代码
 1 #include <iostream>
 2 #include <fstream>
 3 using namespace std;
 4 class  Dog{
 5     public:
 6         int ages;
 7         int weight;
 8         Dog(int w,int a)
 9         {
10             weight=w;
11             ages=a;
12         }
13         Dog(){
14         }
15 };
16 int main()
17 {
18     Dog dog1(5,10);
19     fstream file1("text.txt",ios::out|ios::binary);
20     file1.write((const char*)&dog1,sizeof(dog1));
21     file1.close();    
22     ifstream file2;
23     file2.open("text.txt",ios::in|ios::binary);
24     if(!file2.is_open())
25     {
26         cout<<"文件打开失败"<<endl;
27     }
28     Dog dog2;
29     file2.read((char*)&dog2,sizeof(dog1));
30     cout<<dog2.weight<<endl;
31     cout<<dog2.ages<<endl;
32     file2.close();
33 }
复制代码

 

posted @   新晋软工小白  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示