C++ IO库【学习笔记】

IO库

  • 头文件iostream
    • istream从流读取数据
    • ostream向流写入数据
    • iostream读写流
  • 头文件fstream
    • ifstream从文件流读取数据
    • ofstream向文件流写入数据
    • fstream 读写文件流
  • 头文件sstream
    • istringstream从string流读取数据
    • ostringstream向string流写入数据
    • stringstream 读写string流

继承关系(stringstream也类似,都继承自iostream)

在这里插入图片描述

使用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); //这里将string转换成了string流
        //这里因为string里有三个单词,因此>>三次
        record>>p.name;
        record>>p.phone;
        record>>p.phone2;
        buffer.push_back(p);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值