sstream定义了一个从ostream派生来的ostringstream类,可以将格式化信息写入string对象,在格式化文本进入缓冲区的时候,
如果有必要,将使用动态分配内存来扩大缓冲区。ostringstream有一个成员函数str(),可以返回被初始化为缓冲区内容的字符串。见例:
// strout.cpp -- incore formatting (output)
#include <iostream>
#include <sstream>
#include <string>
int main()
{
using namespace std;
ostringstream outstr; // manages a string stream
string hdisk;
cout << "What's the name of your hard disk? ";
getline(cin, hdisk);
int cap;
cout << "What's its capacity in GB? ";
cin >> cap;
// write formatted information to string stream
outstr << "The hard disk " << hdisk << " has a capacity of "
<< cap << " gigabytes.\n";
string result = outstr.str(); // save result
cout << result; // show contents
return 0;
}
上面的代码中,把hdisk和cap等信息写入outstr中,利用str函数返回缓冲区内容的字符串结果,然后用cout输出result。
istringstream类允许使用istream类的方法读取istringstream对象中的内容。
// strin.cpp -- formatted reading from a char array
#include <iostream>
#include <sstream>
#include <string>
int main()
{
using namespace std;
string lit = "It was a dark and stormy day, and "
" the full moon glowed brilliantly. ";
istringstream instr(lit); // use buf for input
string word;
while (instr >> word) // read a word a time
cout << word << endl;
return 0;
}
输出
可以看出,instr在获取word的内容时,遇到空格就停止。与cin相同
换成:
while (getline(instr,word))
输出