Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7775511
  • 博文数量: 701
  • 博客积分: 2150
  • 博客等级: 上尉
  • 技术积分: 13233
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-29 16:28
个人简介

天行健,君子以自强不息!

文章分类

全部博文(701)

文章存档

2019年(2)

2018年(12)

2017年(76)

2016年(120)

2015年(178)

2014年(129)

2013年(123)

2012年(61)

分类: C/C++

2015-12-17 14:13:10

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

派生关系图:
ios_base <- ios <- ostream <- ostringstream

ostringstream的构造函数形式:
explicit ostringstream ( openmode which = ios_base::out );  
explicit ostringstream ( const string & str, openmode which = ios_base::out );  


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


#include   
#include   
#include   
using namespace std;  
  
void main()  
{  
    ostringstream ostr1; // 构造方式1  
    ostringstream ostr2("abc"); // 构造方式2  
  
  
    ostr1 << "ostr1" << 2012 << endl; // 格式化,此处endl也将格式化进ostr1中  
    cout << ostr1.str();   
  
  
    long curPos = ostr2.tellp(); //返回当前插入的索引位置(即put pointer的值),从0开始   
    cout << "curPos = " << curPos << endl;  
  
    ostr2.seekp(2); // 手动设置put pointer的值  
    ostr2.put('g');     // 在put pointer的位置上写入'g',并将put pointer指向下一个字符位置  
    cout << ostr2.str() << endl;  
      
  
  
    ostr2.clear();  
    ostr2.str("");  
  
    cout << ostr2.str() << endl;  
    ostr2.str("_def");  
    cout << ostr2.str() << endl;  
    ostr2 << "gggghh";    // 覆盖原有的数据,并自动增加缓冲区  
    cout << ostr2.str() << endl;  
}
  
详细用法请参考如下网址:点击打开链接


阅读(1577) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~