zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [已读]Sass与Compass实战
    微信小程序图片变形解决方法
    ES6基础教程一 学习笔记
    微信小程序图片放大预览
    Element ui表格展示多张图片问题
    Element ui表格展示图片问题
    使用element ui 日期选择器获取值后的格式问题
    在vue2.0中使用sass
    微信小程序左滑删除功能
    微信小程序用setData修改数组或对象中的一个属性值
  • 原文地址:https://www.cnblogs.com/pdev/p/3798439.html
Copyright © 2011-2022 走看看