c++文件输入输出流fstream,对输入>>和输出<<重载
2014-07-17 17:57
323 查看
1. fstream 继承自iostream --> 要包含头文件#include<fstream>
2. 建立文件流对象
3. 打开文件夹
4. 测试是否打开成功
5. 进行读写操作
6. 关闭文件
View Code
结果:
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
结果:
相关文章推荐
- C++中输入输出<< 和>>重载,以便适应输出输入一个对象
- C++第九周【任务一】定义Complex类中的<<和>>运算符的重载,实现输入和输出
- C++中cout/cin对于空指针、字符指针的处理,及输入>>、 输出<<操作符的重载
- C++输入操作符>> 输出操作符<<重载
- 第九周 C++任务一。定义Complex类中的<<和>>运算符的重载,实现输入和输出
- c++ 重载 >>(输入) 、<< (输出) 操作符
- c++ 重载 >>(输入) 、<< (输出) 操作符
- c++ 重载 >>(输入) 、<< (输出) 操作符
- 《C++第九周实验报告1-1》--------接第8周任务1,定义Complex类中的<<和>>运算符的重载,实现输入和输出
- 第九周C++报告二。定义Time类中的<<和>>运算符重载,实现时间的输入输出
- 《C++第九周实验报告2-1》---接第8周任务2,定义Time类中的<<和>>运算符重载,实现时间的输入输出
- C++ FAQ学习笔记 15 章 通过 <iostream> 和 <cstdio>输入/输出
- C++ FAQ Lite[15]--通过 <iostream> 和 <cstdio>输入/输出(新)
- 第九周【项目1】在第8周项1的基础上(1)再定义一目运算符 -,-c相当于0-c(2)定义Complex类中的<<和>>运算符的重载,实现输入和输出,改造原程序中对运算结果显示方式,使程序读起来更自然
- 第九周实验报告 任务2 定义Complex类中的<<和>>运算符的重载,实现输入和输出,改造原程序中对运算结果显示方式,使程序读起来更自然。
- 九周任务三:定义分数类中的<<和>>的重载,实现分数的输入和输出
- 第九周任务一(定义Complex类中的<<和>>运算符的重载,实现输入和输出)
- 第九周试验任务1--定义Time类中的<<和>>运算符的重载,实现输入和输出。
- C++第九周【任务二】定义Time类中的<<和>>运算符重载,实现时间的输入输出
- 第九周C++任务三。定义分数类中<<和>>运算符重载,实现分数的输入输出