C++库提供了sstream族,他们使用相同的接口提供程序和string对象之间的I/O;可以使用与cout的ostream方法将格式化信息写入到string对象中,并使用istream方法来读取string对象中的信息;读取string对象中的格式化信息或将格式化信息写入string对象中被称为内核格式化。
头文件sstream定义了ostream的继承类ostringstream类(还有一个基于wostream的wostringstream类用于宽字符集。
ostringstream对象.str()—返回一个被初始化为缓冲区内容的字符串对象,使用str()方法可以”冻结“该对象,这样将不能再写入信息到该对象中。
istringstream类允许使用istream方法族读取istringstream对象中的数据,istringstream对象可以使用string对象进行初始化。
code:
// strout.cpp -- incore formatting (output) #include#include #include int main() { using namespace std; cout << "ostringstream**************************************************************" << endl; 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";//此处并不会输出内容,此处只是将后面的内容插入到outstr流中 string result = outstr.str(); // save result cout << result; // show contents 此处才会输出内容 cout << "istringstream**************************************************************" << endl; 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; }
运行结果:
ostringstream************************************************************** What's the name of your hard disk? Jasmine What's its capacity in GB? 900 The hard disk Jasmine has a capacity of 900 gigabytes. istringstream************************************************************** It was a dark and stormy day, and the full moon glowed brilliantly. D:Prj_C++Self_32Incore_foamattingx64Debug_32Incore_foamatting.exe (进程 864)已退出,代码为 0。 要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。 按任意键关闭此窗口. . .



