1.stringstream字串分割
string line,word;
while(getline(cin,line)){//外层循环持续执行,直至遇到cin的文件结束标识
//以下两行等价于stringstream stream(line);
stringstream stream;
stream.str(line); //将line拷贝给stream,返回void
cout<<stream.str()<<endl;//stream.str()返回stream所保存的string的拷贝
while(stream>>word){//内层循环当stringstream中数据全部读出,会触发"文件结束"信号
<<word<<endl;
}
}
输入:Hello World
输出:Hello World
Hello
World
2.stringstream格式转换
int a=1024;
string b="hello_word";
stringstream stream;
stream<<a<<" "<<b;//将int转化为string
//字符串流通过空格判断一个字符串的结束
cout<<stream.str()<<endl;
int num;
string str;
stream>>num>>str;//将string转化为int
cout<<num<<endl<<str<<endl;
3.其他
3.1 初始化 //①和②等价,无法进行插入操作;③可以进行插入操作
stringstream stream1("string");//①
stream1<<"aaa";
cout<<stream1.str().size()<<endl;
stringstream stream2;
stream2.str("string");//②
stream2<<"aaa";
cout<<stream2.str().size()<<endl;
stringstream stream3;
stream3<<"string";//③
stream3<<"aaa";
cout<<stream3.str().length()<<endl;
运行结果:6
6
9
3.2 stream.str("")和stream.clear()
stringstream stream;
stream<<"567"; int a,b; stream>>a; cout<<a<<endl; stream.clear();//进行多次转换前,必须clear stream<<true; stream>>b; cout<<b<<endl; //str("")表示清除stream内容 //clear()表示清除stream标志位
运行结果:567
1(加clear)
18(不加clear)