• std::ostringstream用法浅析


    ostringstream是C++的一个字符集操作模板类,定义在sstream.h头文件中。ostringstream类通常用于执行C风格的串流的输出操作,格式化字符串,避免申请大量的缓冲区,替代sprintf。

    派生关系图:

    ostringstream
     

    ostringstream的构造函数形式:

    1 explicit ostringstream ( openmode which = ios_base::out );
    2 explicit ostringstream ( const string & str, openmode which = ios_base::out );

    有时候,我们需要格式化一个字符串,但通常并不知道需要多大的缓冲区。为了保险常常申请大量的缓冲区以防止缓冲区过小造成字符串无法全部存储。这时我们可以考虑使用ostringstream类,该类能够根据内容自动分配内存,并且其对内存的管理也是相当的到位。

     1 #include <sstream>
     2 #include <string>
     3 #include <iostream>
     4 using namespace std;
     5 
     6 void main()
     7 {
     8     ostringstream ostr1; // 构造方式1
     9     ostringstream ostr2("abc");    // 构造方式2
    10 
    11 /*----------------------------------------------------------------------------
    12 *** 方法str()将缓冲区的内容复制到一个string对象中,并返回
    13 ----------------------------------------------------------------------------*/
    14     ostr1 << "ostr1" << 2012 << endl;    // 格式化,此处endl也将格式化进ostr1中
    15     cout << ostr1.str(); 
    16 
    17 /*----------------------------------------------------------------------------
    18 *** 建议:在用put()方法时,先查看当前put pointer的值,防止误写
    19 ----------------------------------------------------------------------------*/
    20     long curPos = ostr2.tellp(); //返回当前插入的索引位置(即put pointer的值),从0开始 
    21     cout << "curPos = " << curPos << endl;
    22 
    23     ostr2.seekp(2);    // 手动设置put pointer的值
    24     ostr2.put('g');        // 在put pointer的位置上写入'g',并将put pointer指向下一个字符位置
    25     cout << ostr2.str() << endl;
    26     
    27 
    28 /*----------------------------------------------------------------------------
    29 *** 重复使用同一个ostringstream对象时,建议:
    30 *** 1:调用clear()清除当前错误控制状态,其原型为 void clear (iostate state=goodbit);
    31 *** 2:调用str("")将缓冲区清零,清除脏数据
    32 ----------------------------------------------------------------------------*/
    33     ostr2.clear();
    34     ostr2.str("");
    35 
    36     cout << ostr2.str() << endl;
    37     ostr2.str("_def");
    38     cout << ostr2.str() << endl;
    39     ostr2 << "gggghh";    // 覆盖原有的数据,并自动增加缓冲区
    40     cout << ostr2.str() << endl;
    41 }

    详细用法请参考如下网址:http://www.cplusplus.com/reference/sstream/ostringstream/

  • 相关阅读:
    项目管理【44】 | 项目干系人管理-识别干系人
    移动端开发基础【15】H5和小程序开发注意事项
    召回率recall,IoU, mPA理解,针对video detection领域
    转:batch normalization, instance normalization, layer normalization, group normalization
    自监督(对比学习)资料
    转:非极大值抑制(Non-Maximum Suppression,NMS)
    转:Zero-shot Learning / One-shot Learning / Few-shot Learning
    转:top1错误率、top5正确率
    转:如何理解Inductive bias?
    台式机更新后没有声音了怎么办,Realtek音频管理器
  • 原文地址:https://www.cnblogs.com/520zijuan/p/2913736.html
Copyright © 2020-2023  润新知