//多种类型之间的自动转换,这样可以很方便实现写和读 一般用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;
}