转载于https://blog.csdn.net/shs1992shs/article/details/83051298
stringstream是 C++ 提供的一个字符串流(stream),要使用stringstream,必须包含其头文件:
#include <sstream>
using namespace std;
stringstream ss;
< sstream > 库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。一般情况下使用stringstream就足够,因为字符串要频繁的涉及到输入输出。
< sstream > 使用string对象来代替字符数组,这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即便使用了不正确的格式化符也没有危险。
与文件流fstream类似,通过插入器(<<)和析取器(>>)这两个运算符可以直接对stringstream上的数据输入输出,而将stringstream中的全部数据输出则是使用成员函数str(),其有两种形式:
1、void str() //无参形式,用于将stringstream流中的数据以string字符串的形式输出
2、void str (const string& s)//以字符串为参数,用以覆盖stringstream流中的数据
特别需要注意的是:
// 字符串流清零,将流中的数据全部清除
ss.str("");
ss.clear()成员函数
在对同一个stringstream对象重复赋值,就需要先对流使用clear()函数清空流的状态,此时流占用的内存没有改变,会一直增加(stringstream不主动释放内存),若想改变内存(一般是清除内存,减少内存消耗),需要再配合使用str("")清空stringstream的缓存。
stringstream stream;
int a,b;
ss<<"80";//向流输出数据(写入)
ss>>a;//从流输入数据到a
cout<<"Size of ss = "<<ss.str().length()<<endl;//ss.str()返回一个string对象,再调用其成员函数length()
ss.clear();//清空流
ss.str("");//清空流缓存
cout<<"Size of ss = "<<ss.str().length()<<endl;
ss<<"90";//重新赋值
ss>>b;
cout<<"Size of ss = "<<ss.str().length()<<endl;
运行结果:
Size of ss = 2
Size of ss = 0
Size of ss = 2
80
90
stringstream通常是用来做数据转换的,用于字符串与其他变量类型的转换,相比c库的转换,它更加安全,自动和直接。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str1("How are you? 123 1 4.368");
stringstream ss(str1);//构造函数初始化
cout<<ss.str()<<endl;
string str2;
for(int i=0;i<3;i++)
{
ss>>str2;
cout<<str2<<" ";
}
cout<<endl; //先换行
int a;
ss>>a;
cout<<a<<endl;
bool b;
ss>>b;
cout<<b<<endl;
float c;
ss>>c;
cout<<c<<endl;
ss.clear();
ss.str("I am fine!");//重新赋值
while(ss>>str2)//不断读取
{
cout<<str2<<" ";
}
}
运行结果:
How are you? 123 1 4.368
How are you?
123
1
4.368
I am fine!