C++文本文件的读写
2016-04-18 13:09
465 查看
#include <iostream>
#include <fstream>
using namespace std;
class Student {
public:
char name[10];
int num;
int age;
char addr[15];
friend ostream &operator<<(ostream &out, Student &s);
friend istream &operator>>(iostream &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;
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
ofstream ofile;
ifstream ifile;
ofile.open("d:\\s.txt");
Student s;
for(int i=1; i<=3; i++){
cout<<"请输入第"<<i<<"个学生的姓名 学号 年龄 住址"<<endl;
cin>>s; //调用>>运算符重载函数,输入学生信息
ofile<<s; //调用<<运算符重载函数,将学生信息写入到文件中
}
ofile.close();
cout<<endl<<"读出文件内容"<<endl;
ifile.open("d:\\s.txt");
ifile>>s;
while(!ifile.eof()) {
cout<<s;
ifile>>s;
}
ifile.close();
return 0;
}
#include <fstream>
using namespace std;
class Student {
public:
char name[10];
int num;
int age;
char addr[15];
friend ostream &operator<<(ostream &out, Student &s);
friend istream &operator>>(iostream &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;
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
ofstream ofile;
ifstream ifile;
ofile.open("d:\\s.txt");
Student s;
for(int i=1; i<=3; i++){
cout<<"请输入第"<<i<<"个学生的姓名 学号 年龄 住址"<<endl;
cin>>s; //调用>>运算符重载函数,输入学生信息
ofile<<s; //调用<<运算符重载函数,将学生信息写入到文件中
}
ofile.close();
cout<<endl<<"读出文件内容"<<endl;
ifile.open("d:\\s.txt");
ifile>>s;
while(!ifile.eof()) {
cout<<s;
ifile>>s;
}
ifile.close();
return 0;
}
相关文章推荐
- C/C++ 常见编译错误及解决办法
- C语言指针-------通过调用函数,完成两个数值的交换
- c++文件流操作
- C++中Static作用和使用方法
- c++类的拷贝构造函数、隐式转换、重载的赋值操作符的一些分析和实例
- [C++]关于STL慎重选择删除元素的方法
- 友元类
- leetcode_226_Invert Binary Tree(C++)(easy)
- Java内联函数(华为面试)-java可能比c++更快
- c语言随机数
- [C++11]新特性——引入了nullptr
- 在C++中子类继承和调用父类的构造函数方法
- 在vc++工程中只使用tlb文件的用法
- C++空类的sizeof
- C语言sscanf函数的总结
- 设计模式中的构建者Builder模式&c++
- C++11新特性之智能指针
- cl.exe命令方式编译cpp
- 文件中有一组整数,要求排序后输出到另一个文件中
- leetcode_104._Maximum Depth of Binary Tree(C++)(easy)