一、简单介绍
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
关注
打赏
热门博文
- DevOps实践教程 华为云 系列教程2021 合集
- ❤️Python Django网站开发 2021年最新版教程 合集❤️
- ❤️java多线程并发编程入门 教程合集❤️
- ❤️区块链Hyperledger Fabric 老版本 1.1.0 快速部署安装 教程合集❤️
- ❤️Docker教程小白实操入门 教程合集❤️
- ❤️微信小程序 云开发 教程合集(视频+图文)免费❤️
- C++ boost::asio::io_service创建线程池thread_group简单实例
- C++ error: ‘shared_ptr’ was not declared in this scope
- git 代码回滚回退到指定版本 并 提交
- C++ 得到map中最后一个元素