sstream使用简介

时间:2023-03-09 16:49:30
sstream使用简介

sstream即字符串流.
sstream有三种类:ostringstream:用于输出操作,istringstream:用于输入操作,stringstream:用于输入输出操作
其实我感觉只用第三个就够了-_-||

基本操作:
stringstream buff;
buff.str() 将buff里面的内容当做一个string返回
buff.str("....") 对buff赋值
buff.clear() 清空buff
可以使用流操作符>>和<<, 类比cin,cout.

建议在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象),而在中间使用clear()函数清空.stringstream对象的构造和析构函数通常是非常耗费CPU时间的.

其实sstream最有用的还是在类型转换里面,把string转换成int,float等类型.
来看个例子吧:

 #include <iostream>
#include <sstream>
using namespace std; int main()
{
cout << "Hello world!" << endl; ostringstream buff1;
buff1<<"Sample1 #1";
string st1=buff1.str();
cout<<st1<<endl; istringstream buff2;
buff2.str("Sample2 #2");
string st2="ReWrite2";
//buff2>>st2;
getline(buff2,st2);
cout<<st2<<endl; stringstream buff3;
buff3<<"Sample3 #3";
string st3=buff3.str();
cout<<st3<<endl; buff3.clear();
buff3.str("Sample4 #4");
string st4="ReWirte4";
buff3>>st4;
cout<<st4<<endl; //----------------------------------------------------
cout<<endl;
//---------------------------------------------------- stringstream buff4;
buff4.str("");
int i;
buff4>>i;
cout<<i<<endl; buff4.clear();
buff4.str("233.33");
double j;
buff4>>j;
cout<<j<<endl; return ;
}

line9--12:对buff1赋值,再赋给字符串st1
line21--24:同上,只是改了个类型...

line14--19和line26--30:都是用str()函数给buff赋值,然后写到字符串里.
但是二者存在不同:
14--19使用的getline,会读入一整行(当然包括了空格后面的内容),所以输出了完整的一句.
而26--30是使用的流操作符.类比cin我们不难发现,在buff3>>st4时,buff3空格及后面的内容都被略掉了.

来看运行结果:

sstream使用简介

当然最有实用价值的还是line36--40和line42--46,分别实现了string->int和string->double的类型转换.

参考:

http://blog.163.com/zhuandi_h/blog/static/180270288201291710222975/
http://blog.sina.com.cn/s/blog_5c8c24a90100emye.html