C++IO处理

//多种类型之间的自动转换,这样可以很方便实现写和读  一般用stringstream    sstream进行处理
 ostringstream format_message;
    format_message << "val1: " << 512 << "\n"
                   << "val2: " << 1024 << "\n";
    istringstream input_istring(format_message.str());
    int val1 = 0;
    int val2 = 0;
    input_istring >> val1 >> val2;///发生异常了,所以要用下面的input_istring.clear();重载了出错状态
 cout<<val1<<" "<<val2<<endl;
 cout<<input_istring.rdstate()<<endl;
    input_istring.clear();
    string dump;
    input_istring >> dump >> val1 >> dump >> val2;
    cout << val1 <<  " " << val2 << endl;
return 0;
}

//读一行数据放到line中,然后绑定istringstream,然后进行有格式的输出。如以word方式输出:

 string line,word;
   while(getline(cin,line)){
      istringstream stream(line);
      while(stream>>word) cout<<word<<"******"<<endl;//word 的string以空格为结尾。

    }

//读文件

 

#include <stdio.h>
#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>//setw setpre.. setfill
#include <fstream>
#include <sstream>
#include<stdexcept>
using namespace std;
//读单词文件,并把它列出来
ifstream& open_file(ifstream &in,const string &file){
    in.close();
 in.clear();
 in.open(file.c_str());
 return in;
}
int main(int argc, char **argv)
{

    ifstream map_file;
 if(argc!=2)
    throw runtime_error("wrong number of argument");
 if(!open_file(map_file,argv[1]))  throw runtime_error("wrong open of file");
   string word,line;
   while(getline(map_file,line)){
      istringstream stream(line);
      while(stream>>word) cout<<word<<" ";//word 的string以空格为结尾。
   cout<<endl;
    }
 
return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值