#include<iostream>
#include<algorithm>
#include<sstream>
using namespace std;
int main(){
//字符串转数字
//方法1
stringstream ss;
string s="1234";
int i;
ss<<s;
ss>>i;
cout<<i<<endl;
//方法2
//stoi(字符串,起始位置,n进制),将n进制的字符串转化为十进制
int j=stoi(s); //不写默认为十进制
cout<<j<<endl;
int k=stoi("1010",0,2);
cout<<k<<endl;
ss.clear(); //不clear会出错
//数字转字符串
//方法1
int a=233;
string out;
ss<<a;
ss>>out;
cout<<out<<endl;
//方法2
cout<<to_string(a)<<endl;
//字符串转化为其他类型
string test="-123 9.87 welcome to, 989, test!";
istringstream iss;
iss.str(test);
string s1;
cout<<"按照空格读取字符串"<<endl;
while(iss>>s){
cout<<s<<endl; //按空格读取string
}
istringstream strm(test);
int ii;
float f;
char c;
char buff[1024];
strm>>i;
cout<<"读取int类型"<<ii<<endl;
strm>>f;
cout<<"读取float类型"<<f<<endl;
strm>>c;
cout<<"读取char类型"<<c<<endl;
strm>>buff;
cout<<"读取buffer类型"<<buff<<endl;
strm.ignore(100,',');
int m;
strm>>m;
cout<<"忽略,读取int类型:"<<m<<endl;
//多个字符串拼接
stringstream sstream;
sstream<<"first"<<" "<<"string,";
sstream<<" second string";
cout<<"strResult is:"<<sstream.str()<<endl;
//清空sstream
sstream.str("");
sstream<<"third string";
cout<<"After clear, strResult is:"<<sstream.str()<<endl;
return 0;
}