您的位置:首页 > 编程语言 > C语言/C++

c++文件输入输出流fstream,对输入>>和输出<<重载

2014-07-17 17:57 323 查看
1. fstream 继承自iostream --> 要包含头文件#include<fstream>

2. 建立文件流对象

3. 打开文件夹

4. 测试是否打开成功

5. 进行读写操作

6. 关闭文件

#include<iostream>
#include<fstream>
using namespace std;

class student{
public:
char name[10];
int num;
int age;
char addr[20];
friend ostream & operator<<(ostream &out, student &s);
friend istream & operator>>(istream &in, student &s);
};
ostream & operator<<(ostream &out, student &s){
out << s.name << " " << s.num << " " << s.age << " " << s.addr << endl;
return out;
}
istream & operator>>(istream &in, student &s){
in >> s.name >> s.num  >> s.age >> s.addr;
return in;
}
int main(){
ifstream ifile;
ofstream ofile;
ofile.open("d:\\s.txt");

student s;
for (int i = 1; i <= 3; i++){
cout << "请输入第" << i << "个学生的姓名 学号 年龄 地址" << endl;
cin >> s;   //调用>>运算符重载函数,输入学生信息
ofile << s; //调用<<运算符重载函数,将学生信息写入到文件中
}
ofile.close();

cout << "\n读出文件内容" << endl;
ifile.open("d:\\s.txt");
ifile >> s;
while (!ifile.eof()){
cout << s;
ifile >> s;
}
ifile.close();
int i;
cin >> i;
return 0;
}


View Code
结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐