istringstream,由istream派生出来的,用于读一个string的对象;
ostringstream,由ostream派生出来的,用于写一个string的对象;
stringstream,由iostream派生出来,同时提供了对于stringstream对象的功能!!
要是用上述的三个类,必须包含sstream头文件!!
stringstream对象的一个重要的功能是让我们更方便的操作string对象!
1.stringstream::str(); returns a string object with a copy of the current contents of the stream.
2.stringstream::str (const string& s); sets s as the contents of the stream, discarding any previous contents.
3.stringstream清空,stringstream s; s.str("");
4.实现任意类型的转换
template<typename out_type, typename in_value>
out_type convert(const in_value & t){
stringstream stream;
stream<<t;//向流中传值
out_type result;//这里存储转换结果
stream>>result;//向result中写入值
return result;
例子:可以在定义这个对象的时候进行初始化操作:
#include<sstream>
#include<string>
#include<iostream>
using namespace std;
int main()
{
string str;
int i = 12345;
stringstream ss;
ss << i;
str = ss.str();
return 0;
}
其中ss.str()返回的是一个流中保存的string对象的副本,这样就实现了通过流对象对一个string对象的赋值操作从而增加string对象操作的灵活性!
2、另外一个很重要的方面就是可以通过stringstream来实现数据类型的转换将一个string对象中保存的字符串还原成原来的数据结构!
#include<sstream>
#include<string>
#include<iostream>
using namespace std;
int main()
{
string str = “12345true”;