1.标准库定义的三中类型的字符串流(#include<sstream>)
istringstream,ostringstream,stringstream
*stringstream:
构造函数:
explicit stringstream (ios_base::openmode which = ios_base::in | ios_base::out);
explicit stringstream (const string& str,
ios_base::openmode which = ios_base::in | ios_base::out);
方法:
string str() const;
void str (const string& s)
eg:
string str("hello");
stringstream strm; //创建自由的stringstream对象
stringstream strm1(str); //创建存储str的副本的stringstream对象
strm1.str(); //返回strm1中存储的string类型对象
strm.str(str); //将string类型的str复制给strm,返回void
应用一:将一句话拆分成单词
int main()
{
string line,word;
getline(cin,line); //输入hello how are you
istringstream strm(line); //创建存储line的副本的stringstream对象
int count=0;
while(strm>>word)
{
cout<<++count<<":"<<word<<'\t'; //1: hello 2:how 3:are 4:you
}
return 0;
}
应用二:格式转换/格式化
int main()
{
string total,wipe;
int val1=1,val2=2,val3=0,val4=0;
ostringstream write;
write<<"val1: "<<val1<<ends<<"val2: "<<val2<<endl; //将表达式转为字符串(格式转换)
total=write.str();
cout<<total<<endl; //输出val1: 1 val2:2
istringstream read(total);
read>>wipe>>val3>>wipe>>val4; //将字符串的内容提取出来,注意提取时需对应写入时的顺序(格式化)
cout<<"val3: "<<val3<<ends<<"val4: "<<val4<<endl; //输出val3: 1 val4:2
return 0;
}
istringstream,ostringstream,stringstream
*stringstream:
构造函数:
explicit stringstream (ios_base::openmode which = ios_base::in | ios_base::out);
explicit stringstream (const string& str,
ios_base::openmode which = ios_base::in | ios_base::out);
方法:
string str() const;
void str (const string& s)
eg:
string str("hello");
stringstream strm; //创建自由的stringstream对象
stringstream strm1(str); //创建存储str的副本的stringstream对象
strm1.str(); //返回strm1中存储的string类型对象
strm.str(str); //将string类型的str复制给strm,返回void
应用一:将一句话拆分成单词
int main()
{
string line,word;
getline(cin,line); //输入hello how are you
istringstream strm(line); //创建存储line的副本的stringstream对象
int count=0;
while(strm>>word)
{
cout<<++count<<":"<<word<<'\t'; //1: hello 2:how 3:are 4:you
}
return 0;
}
应用二:格式转换/格式化
int main()
{
string total,wipe;
int val1=1,val2=2,val3=0,val4=0;
ostringstream write;
write<<"val1: "<<val1<<ends<<"val2: "<<val2<<endl; //将表达式转为字符串(格式转换)
total=write.str();
cout<<total<<endl; //输出val1: 1 val2:2
istringstream read(total);
read>>wipe>>val3>>wipe>>val4; //将字符串的内容提取出来,注意提取时需对应写入时的顺序(格式化)
cout<<"val3: "<<val3<<ends<<"val4: "<<val4<<endl; //输出val3: 1 val4:2
return 0;
}