IO库
- 头文件iostream
- istream从流读取数据
- ostream向流写入数据
- iostream读写流
- 头文件fstream
- ifstream从文件流读取数据
- ofstream向文件流写入数据
- fstream 读写文件流
- 头文件sstream
- istringstream从string流读取数据
- ostringstream向string流写入数据
- stringstream 读写string流
继承关系(stringstream也类似,都继承自iostream)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5d76caaf9747def54f2348a5d6f44611.png)
使用IO库:
使用fstream
#include <iostream>
#include <fstream>
#include <sstream>
#include <Person.hpp>
#include <vector>
using namespace std;
int main()
{
string file_name = "../data/data.txt";
cout<<"1.从文件中读取数据---------------"<<endl;
ifstream input;
input.open(file_name);
if(!input) {
cout<<"打开文件失败"<<endl;
return 0;
}
cout<<"打开文件成功"<<endl;
Person p;
vector<Person> buffer, buffer2;
cout<<"开始读取..."<<endl;
while(read(input,p)){
buffer.push_back(p);
}
cout<<"读取结果:"<<endl;
for(Person p:buffer){
cout<<p.name<<" "<<p.age<<" "<<p.weight<<endl;
}
input.close();
cout<<"2.向文件中写入数据---------------"<<endl;
ofstream output("../data/data2.txt");
if(!output){
cout<<"打开文件失败"<<endl;
return 0;
}
cout<<"打开文件成功"<<endl;
for(Person p:buffer){
if(print(output, p)) cout<<"写入成功"<<endl;
}
output.close();
return 0;
}
- Person.hpp文件中对read和print的定义:
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
string name;
unsigned age = 0;
double weight = 0.0;
string phone;
string phone2;
string getname()const{return name;}
};
ostream &print(ostream&, const Person&);
istream &read(istream&, Person&);
ostream &print(ostream &os, const Person &item)
{
os<<item.getname()<<" "<<item.age<<" "<<item.weight<<endl;
return os;
}
istream &read(istream &is, Person &item)
{
is>>item.name>>item.age>>item.weight;
return is;
}
使用sstream:
ifstream input;
input.open("../data/data.txt");
if(!input) {
cout<<"打开文件失败"<<endl;
return 0;
}
string line;
while(getline(input,line)){
cout<<"当前读取的行内容:"<<line<<endl;
istringstream record(line);
record>>p.name;
record>>p.phone;
record>>p.phone2;
buffer.push_back(p);
}