Pentium.Labs

System全家桶:https://zhuanlan.zhihu.com/c_1238468913098731520

导航

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等类型.
来看个例子吧:

 1 #include <iostream>
 2 #include <sstream>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     cout << "Hello world!" << endl;
 8 
 9     ostringstream buff1;
10     buff1<<"Sample1 #1";
11     string st1=buff1.str();
12     cout<<st1<<endl;
13 
14     istringstream buff2;
15     buff2.str("Sample2 #2");
16     string st2="ReWrite2";
17     //buff2>>st2;
18     getline(buff2,st2);
19     cout<<st2<<endl;
20 
21     stringstream buff3;
22     buff3<<"Sample3 #3";
23     string st3=buff3.str();
24     cout<<st3<<endl;
25 
26     buff3.clear();
27     buff3.str("Sample4 #4");
28     string st4="ReWirte4";
29     buff3>>st4;
30     cout<<st4<<endl;
31 
32 //----------------------------------------------------
33 cout<<endl;
34 //----------------------------------------------------
35 
36     stringstream buff4;
37     buff4.str("23333");
38     int i;
39     buff4>>i;
40     cout<<i<<endl;
41 
42     buff4.clear();
43     buff4.str("233.33");
44     double j;
45     buff4>>j;
46     cout<<j<<endl;
47 
48     return 0;
49 }
View Code

 

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

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

 

来看运行结果:


当然最有实用价值的还是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

posted on 2014-06-20 01:15  Pentium.Labs  阅读(3384)  评论(0编辑  收藏  举报



Pentium.Lab Since 1998