加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

std::ostringstream用法详解

(2013-04-02 11:21:58)
标签:

标准c

分类: 编程开发技术

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

派生关系图:

 

http://www.cplusplus.com/img/arrow.gif http://www.cplusplus.com/img/arrow.gif http://www.cplusplus.com/img/arrow.gif
ostringstream

 

ostringstream的构造函数形式:

 

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

 

  1. #include   
  2. #include   
  3. #include   
  4. using namespace std;  
  5.   
  6. void main()  
  7.  
  8.     ostringstream ostr1; // 构造方式1  
  9.     ostringstream ostr2("abc"); // 构造方式2  
  10.   
  11.   
  12.     ostr1 << "ostr1" << 2012 << endl; // 格式化,此处endl也将格式化进ostr1中  
  13.     cout << ostr1.str();   
  14.   
  15.   
  16.     long curPos ostr2.tellp(); //返回当前插入的索引位置(即put pointer的值),从0开始   
  17.     cout << "curPos " << curPos << endl;  
  18.   
  19.     ostr2.seekp(2); // 手动设置put pointer的值  
  20.     ostr2.put('g');     // 在put pointer的位置上写入'g',并将put pointer指向下一个字符位置  
  21.     cout << ostr2.str() << endl;  
  22.       
  23.   
  24.   
  25.     ostr2.clear();  
  26.     ostr2.str("");  
  27.   
  28.     cout << ostr2.str() << endl;  
  29.     ostr2.str("_def");  
  30.     cout << ostr2.str() << endl;  
  31.     ostr2 << "gggghh"   // 覆盖原有的数据,并自动增加缓冲区  
  32.     cout << ostr2.str() << endl;  
  33.  

详细用法请参考如下网址:点击打开链接

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有