<sstream>定义了三个类:istringstream,ostringstream,stringstream,分别用来进行流的输入、输出、输入输出操作。
<sstream>主要用来数据类型转换,<sstream>使用string对象代替字符数组snprintf,避免缓冲区溢出,其传入参数和目标对象的类型会被自动推导出来,因此不存在错误的格式化符的问题。安全、自动、直接。
数据类型转换:
#include<string>
#include<iostream>
#include<sstream>
#include<stdio.h>
using namespace std;
//数据类型转换
int main(){
stringstream sstream;
string strResult;
int nValue=1000;
sstream<<nValue;//将int型的放到输入流
sstream>>strResult;//从流中拿出来赋给string类型
cout<<"cout strResult is:"<<strResult<<endl;
printf("printf strResult is:%s",strResult.c_str());
return 0;
}
结果:
cout strResult is:1000
printf strResult is:1000
多个字符串拼接:
#include<string>
#include<iostream>
#include<sstream>
#include<stdio.h>
using namespace std;
int main(){
stringstream sstream;
//将多个字符串放到sstream
sstream<<"first"<<" "<<"string,";
sstream<<" second string";
cout<<"strResult is:"<<sstream.str()<<endl;//使用 str() 方法,将 stringstream 类型转换为 string 类型
sstream.str("");//清空sstream 必须使用 sstream.str("")方式;clear()方法适用于进行多次数据类型转换的场景
sstream<<"third string";
cout<<"After clear,strResult is:"<<sstream.str()<<endl;
return 0;
}
结果:
strResult is:first string, second string
After clear,strResult is:third string
stringstream的清空:
#include<string>
#include<iostream>
#include<sstream>
#include<stdio.h>
using namespace std;
int main(){
stringstream sstream;
int first,second;
sstream<<"456";//流入字符串
sstream>>first;//转换为int
cout<<first<<endl;
sstream.clear();//在进行多次类型转换前,必须先运行clear()
sstream<<true;//流入bool值
sstream>>second;//转换为 int
cout<<second<<endl;
return 0;
}
结果:456 1