c语言ofstream头文件,C++/C++11中头文件<sstream>介绍

本文详细介绍了C++中的内存流处理,重点讨论了<sstream>头文件中的ostringstream、istringstream和stringstream类。这些类允许将内存中的字符串作为输入输出流进行操作。文中通过示例代码展示了如何使用这些类的构造函数、str()、rdbuf()、swap()等成员函数进行数据的读写和转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++使用标准库类来处理面向流的输入和输出:(1)、iostream处理控制台IO;(2)、fstream处理命名文件IO;(3)、stringstream完成内存string的IO。

类fstream和stringstream都是继承在类iostream的。输入类都继承自istream,输出类都继承自ostream。因此,可以在istream对象上执行的操作,也可在ifstream或istringstream对象上执行。继承自ostream的输出类也有类似情况。

string流:sstream头文件定义了三个类型来支持内存IO,这些类型可以向string写入数据,从string读取数据,就像string是一个IO流一样。

istringstream从string读取数据,ostringstream向string写入数据,而头文件stringstream既可从string读数据也可向string写数据。与fstream类型类似,头文件sstream中定义的类型都继承iostream头文件中定义的类型。除了继承得来的操作,sstream中定义的类型还增加了一些成员来管理与流相关联的string.

ostringstream只支持<>操作符,stringstream支持<>操作符。

0818b9ca8b590ca3270a3433284dd417.png

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "sstream.hpp"

#include

#include // ostringstream/istringstream/stringstream

#include

// reference: http://www.cplusplus.com/reference/sstream/ostringstream/

int test_ostringstream()

{

// ostringstream: Output stream class to operate on strings

// 1. rdbuf: Returns a pointer to the internal stringbuf object

std::ostringstream oss1;

// using stringbuf directly

std::stringbuf *pbuf = oss1.rdbuf();

pbuf->sputn("Sample string", 13);

std::cout << pbuf->str() << std::endl;

// 2. str(): returns a string object with a copy of the current contents of the stream

// str(const string& s): sets s as the contents of the stream, discarding any previous contents.

// The object preserves its open mode: if this includes ios_base::ate,

// the writing position is moved to the end of the new sequence

std::ostringstream oss2;

oss2 << "One hundred and one: " << 101;

std:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值