ostringstream是C++的一个字符集操作模板类,定义在sstream.h头文件中。ostringstream类通常用于执行C风格的串流的输出操作,格式化字符串,避免申请大量的缓冲区,替代sprintf。
派生关系图:
ostringstream的构造函数形式:
- explicit ostringstream ( openmode which = ios_base::out );
- explicit ostringstream ( const string & str, openmode which = ios_base::out );
有时候,我们需要格式化一个字符串,但通常并不知道需要多大的缓冲区。为了保险常常申请大量的缓冲区以防止缓冲区过小造成字符串无法全部存储。这时我们可以考虑使用ostringstream类,该类能够根据内容自动分配内存,并且其对内存的管理也是相当的到位。
- #include <sstream>
- #include <string>
- #include <iostream>
- using namespace std;
-
- void main()
- {
- ostringstream ostr1;
- ostringstream ostr2("abc");
-
-
-
-
- ostr1 << "ostr1" << 2012 << endl;
- cout << ostr1.str();
-
-
-
-
- long curPos = ostr2.tellp();
- cout << "curPos = " << curPos << endl;
-
- ostr2.seekp(2);
- ostr2.put('g');
- cout << ostr2.str() << endl;
-
-
-
-
-
-
-
- ostr2.clear();
- ostr2.str("");
-
- cout << ostr2.str() << endl;
- ostr2.str("_def");
- cout << ostr2.str() << endl;
- ostr2 << "gggghh";
- cout << ostr2.str() << endl;
- }