您当前的位置: 首页 >  c++
  • 0浏览

    0关注

    1477博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++ std::ostringstream 是什么 怎么用

软件工程小施同学 发布时间:2021-08-20 14:09:55 ,浏览量:0

一、简单介绍

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

派生关系图:

二、ostringstream的基本使用

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

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

三、注意事项

std::ostringstream::str()返回的是临时对象,不能对其直接操作。

例如会有如下误用:

const char *  pBuffer  =  oss.str().c_str(); 注意pBuffer指向的内存已被析构!!  

#include   
#include   
#include   
using namespace std;  
  
void main()  
{  
    ostringstream ostr1; // 构造方式1  
    ostringstream ostr2("abc"); // 构造方式2  
  
/*---------------------------------------------------------------------------- 
*** 方法str()将缓冲区的内容复制到一个string对象中,并返回 
----------------------------------------------------------------------------*/  
    ostr1             
关注
打赏
1665320866
查看更多评论
0.8495s