stringstream是字符串流。它將流與存儲在內存中的string對象綁定起來。ios
在多種數據類型之間實現自動格式化。ide
1 stringstream對象的使用spa
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) 12 { 13 cout<<word<<endl; 14 } 15 } 16 return 0; 17 }
輸入:shanghai no1 school 1989code
輸出:shanghi no1 school 1989對象
shanghaiblog
no1內存
schoolci
1989字符串
2stringstream提供的轉換和格式化get
1 #include <sstream> 2 #include <iostream> 3 using namespace std; 4 int main() 5 { 6 int val1 = 512,val2 = 1024; 7 stringstream ss; 8 9 //將int類型讀入ss,變爲string類型 10 ss<<"val1: "<<val1<<endl //"vall:"此處有空格,字符串流是經過空格判斷一個字符串的結束 11 <<"val2: "<<val2<<endl; 12 cout<<ss.str(); 13 string dump; 14 int a,b; 15 16 //提取512,1024保存爲int類型。固然,若是a,b聲明爲string類型 17 //那麼這兩個字面值常量相應保存爲string類型 18 ss>>dump>>a>>dump>>b; 19 cout<<a<<" "<<b<<endl; 20 return 0; 21 }
輸出爲:val1: 512
val2: 1024
512 1024
3其餘注意
stringstream不會主動釋放內存(或許是爲了提升效率),但若是你要在程序中用同一個流,反覆讀寫大量的數據,將會形成大量的內存消 耗,因些這時候,須要適時地清除一下緩衝 (用 stream.str("") )
#include <cstdlib> #include <sstream> #include <iostream> using namespace std; int main() { stringstream ss; string s; ss<<"shanghai no1 school"; ss>>s; cout<<"size of stream= "<<ss.str().length()<<endl; cout<<"s: "<<s<<endl; ss.str(""); cout<<"size of stream= "<<ss.str().length()<<endl; return 0; }
輸出:
size of stream = 19
s: shanghai
size of stream = 0