定义一个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 }
标签:练习题,file1,weight,int,ages,Dog,PTA,dog1 From: https://www.cnblogs.com/Lyh3012648079/p/17403083.html