C++中的输入输出分为三种:基于控制台的I/O,即istream、ostream、iostream;基于文件的I/O,即ifstream、ofstream、fstream;基于字符串的I/O,即istringstream、ostringstream、stringstream.
C++引入了ostringstream、istringstream、stringstream这三个类,要使用它们创建对象就必须包含头文件sstream。其中ostringstream继承自ostream、istringstream继承自istream、stringstream继承自iostream。这三个类内部除了拥有string buffer之外,还保持了一系列的从ios_base和ios继承而来的格式化字段,因此可以格式化输入/输出。
ostringstream的构造
ostringstream (ios_base::openmode which = ios_base::out);
ostringstream (const string& str, ios_base::openmode which = ios_base::out);
ostringstream的方法
string str() const; -- 将字符串缓冲区中的内容复制到一个string对象中,并返回该对象
void str(const string& s); -- 清除缓冲区原有数据并将字符串s送入字符串缓冲区
istringstream的构造
istringstream (ios_base::openmode which = ios_base::in);
istringstream (const string& str, ios_base::openmode which = ios_base::in);
istringstream的方法
string str() const; -- 将字符串缓冲区中的内容复制到一个string对象中,并返回该对象
void str(const string& s); -- 清除缓冲区原有数据并将字符串s送入字符串缓冲区
stringstream的构造
stringstream (ios_base::openmode which = ios_base::in | ios_base::out);
stringstream (const string& str, ios_base::openmode which = ios_base::in | ios_base::out);
stringstream的方法
string str() const; -- 将字符串缓冲区中的内容复制到一个string对象中,并返回该对象
void str(const string& s); -- 清除缓冲区原有数据并将字符串s送入字符串缓冲区
注:
1.openmode取值为ios_base::in、ios_base::out、ios::base::ate,其他几种openmode如ios_base::app、ios_base::trunc是否有效取决于库的实现;
2.字符串流的ios_base::out并不会像文件流中的那样自动清除原有内容(因为文件流中只有ios::out时相当于ios::out | ios::trunc,而字符串流中则不会)
3.str()方法会保持openmode不变;
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
//ostringstream类
ostringstream foo; //构造方式一
ostringstream bar("hello", ios_base::ate); //构造方式二
foo.str("Test string"); //清空原有数据并将Test string送入foo的string buffer中,此时内容为Test string
bar.str("Test string"); //清空原有数据并将Test string送入bar的string buffer中,此时内容为Test string
foo<<; //将101送入foo的string buffer中,此时foo的string buffer中的内容为101t string
bar<<; //将101送入bar的string buffer中,此时bar的string buffer中的内容为Test string101
cout<<foo.str()<<endl; //101t string
cout<<bar.str()<<endl; //Test string101 cout<<endl; //istringstream类
istringstream istr1; //构造方式一
istringstream istr2("hello", ios_base::ate); //构造方式二
istr1.str("Test string"); //清空原有数据并将Test string送入istr1的string buffer中,此时内容为Test string
istr2.str("Test string"); //清空原有数据并将Test string送入istr2的string buffer中,此时内容为Test string
string word;
while(istr1>>word) //逐单词读取istr1的string buffer中的数据
cout<<word<<endl; //Test\nstring
cout<<endl;
while(istr2>>word) //逐单词读取istr2的string buffer中的数据
cout<<word<<endl; //Test\nstring cout<<endl; //stringstream类
stringstream ss;
ss<<<<" "<<;
int x, y;
ss>>x>>y;
cout<<"x:"<<x<<"\n"<<"y:"<<y<<endl; cout<<endl; //格式化
ostringstream out;
char* str = "hello world";
float num = 314.57f;
out<<setprecision()<<fixed<<str<<num<<endl; //此处endl也将被送入string buffer
cout<<out.str();
cout<<"format output complete.\n"; system("pause");
return ;
}