c++Primer第八章:IO流

文件流

文件模式

方式含义
in
out写,默认截断
app写前定位到末尾
ate打开文件定位到末尾
trunc截断文件,就是之前文本内容全部不要了
binary二进制方式

文件流头文件

项目Value
ifstream
ostream
fstream读写(一般用这个就够了)

代码

ifstream input(argv[1]);//打开销售记录文件
ofstream output(argv[2]);//打开输出文件
sales_data total;
if(read(input,total)){
   sales_data trans;
   while(read(input,trans)){
       if(total.isbn()==trans.isbn())
           total.combine(trans);
       else{
           print(output,total)<<endl;
           total = trans;
       }
   }
   print(output,total);
}
else cerr <<"No data" <<endl;
for(auto p = argv + 1 ;p != argv + argc;p ++){
   ifsream input(*p);
   	if(input){...}
   else cerr<<"no sucn file"<<endl;
}

运行在这里插入图片描述
结果
在这里插入图片描述

string流

头文件

项目Value
sstream向string读写文件

模式

项目Value
istringstream
ostringstream
stringstream读写

string流每次输出以空格为分割,即>>时;

代码

#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;

struct PersonInfo
{
    string name;
    vector<string> phones;
};

int main(){
    string line,word;
    vector<PersonInfo> people;
    while(getline(cin,line)){
        PersonInfo info;
        istringstream record(line);
        record >> info.name;
        while(record>>word){
            info.phones.push_back(word);
        }
        people.push_back(info);
    }
    for(const auto &entry : people){
        ostringstream formated,badnumber;
        for(const auto &nums:entry.phones){
            if (nums.size()<6)
                badnumber<<" "<<nums;
            else
                formated<<" "<<nums;
            
        }
        if(badnumber.str().empty())
        //直接转成string输出了
            cout << entry.name <<" "<<formated.str()<<endl;
        else
            cerr << "input error: "<<entry.name <<"invalid number: "<<badnumber.str()<<endl; 
    }
}

结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值