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支持<>操作符。
下面是从其他文章中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: