输入输出流(C++)

一、问题描述

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

二、代码实现

 1 #include <fstream>
 2 #include <iostream>
 3 using namespace std;
 4 class Dog{
 5     private:
 6         int age,weight;
 7     public:
 8         Dog(int w=0,int a=0)
 9         {
10             age=a;
11             weight=w;
12         }
13         int getweight()
14         {
15             return weight;
16         }
17         int getage()
18         {
19             return age;
20         }
21         void show()
22         {
23             cout<<weight<<" "<<age<<endl;
24         }    
25         void change(int m,int n)
26         {
27             weight=m;
28             age=n;
29         }
30 };
31 int main()
32 {
33     Dog dog1(5,10);
34     Dog dog2;
35     int x,y;
36     x=dog1.getweight();
37     y=dog1.getage();
38     ofstream outfile("outfile.txt",ios::out|ios::binary);
39     if(!outfile)
40     {
41         cerr<<"Open or creat file erro."<<endl;
42         return 0;
43     }        
44     else
45     {
46         outfile<<x<<" "<<y<<endl;
47         outfile.close();
48     }
49     dog1.show();
50     ifstream infile("outfile.txt",ios::in|ios::binary);
51     if(!infile)
52     {
53         cerr<<"Open or creat file erro."<<endl;
54         return 0;
55     }
56     else
57     {
58         infile>>x;
59         infile.seekg(1,ios::cur);//从当前位置右移一个位置,即相当于一个空格
60         infile>>y;
61         dog2.change(x,y);    
62         infile.close();
63     }
64     dog2.show();
65     return 0;
66 }

 

posted on 2023-05-17 21:37  轻挼草色  阅读(31)  评论(0)    收藏  举报