原帖地址:https://zhidao.baidu.com/question/580048330.html
stringstream是字符串流。它将流与存储在内存中的string对象绑定起来。
在多种数据类型之间实现自动格式化。
1.stringstream对象的使用
1 #include<sstream>
2 #include<iostream>
3 using namespace std;
4 int main()
5 {
6 string line,word;
7 while(getline(cin,line))
8 {
9 stringstream stream(line);
10 cout<<stream.str()<<endl;
11 while(stream>>word){cout<<word<<endl;}
12 }
13 return 0;
14 }
输入:shanghai no1 school 1989
输出:shanghi no1 school 1989
shanghai
no1
school
1989
2.stringstream提供的转换和格式化
程序:
1 #include<sstream>
2 #include<iostream>
3 using namespace std;
4 int main()
5 {
6 int val1 = 512,val2 =1024;
7 stringstream ss;
8 ss<<"val1: "<<val1<<endl //“val1: "此处有空格,字符串流是通过空格判断一个字符串的结束
9 <<"val2: "<<val2<<endl;
10 cout<<ss.str();
11
12 string dump;
13 int a,b;
14 ss>>dump>>a
15 >>dump>>b;
16 cout<<a<<" "<<b<<endl;
17 return 0;
18 }
输出为:val1: 512
val2: 1024
512 1024
第一处黑体字部分:将int类型读入ss,变为string类型
第二处黑体字部分:提取512,1024保存为int类型。当然,如果a,b声明为string类型,那么这两个字面值常量相应保存为string类型
3.其他注意
stringstream不会主动释放内存(或许是为了提高效率),但如果要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消 耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )
1 #include <cstdlib>
2 #include<iostream>
3 #include<sstream>
4 using namespace std;
5 int main()
6 {
7 stringstream ss;
8 string s;
9 ss<<"shanghai no1 school";
10 ss>>s;
11 cout<<"size of stream = "<<ss.str().length()<<endl;
12 cout<<"s: "<<s<<endl;
13 ss.str("");
14 cout<<"size of stream = "<<ss.str().length()<<endl;
15 }
输出:
size of stream = 19
s: shanghai
size of stream = 0