1.頭文件:#include<sstream>
2.stringstream是C++提供的串流(stream)物件,其中:
clear()重置流的標志狀態;str()清空流的內存緩沖,重復使用內存消耗不再增加!
在使用stringstream時遇到的問題:
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char * argv[]) { stringstream stream; int a,b; stream<<"80"; stream>>a; stream<<"90"; stream>>b; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
運行結果:

預期b為90,但是出現-858993460,這是由於stringstream重復使用時,沒有清空導致的。
修改之后:
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char * argv[]) { stringstream stream; int a,b; stream<<"80"; stream>>a; stream.clear(); stream<<"90"; stream>>b; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
運行結果:

但是clear()僅僅清空標志位,並沒有釋放內存。
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char * argv[]) { stringstream stream; int a,b; stream<<"80"; stream>>a; stream.clear(); cout<<"Size of stream = "<<stream.str().length()<<endl; stream<<"90"; stream>>b; cout<<"Size of stream = "<<stream.str().length()<<endl; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
clear()之后,雖然結果正確了,但是stream占用的內存卻沒有釋放!在實際的應用中,要是多次使用stringstream,每次都增加占用的內存。

可以利用stringstream.str("")來清空stringstream。
void str ( const string & s ); // copies the content of string s to the string object associated with the string stream buffer. The function effectivelly calls rdbuf()->str(). Notice that setting a new string does not clear the error flags currently set in the stream object unless the member function clear is explicitly called.
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char * argv[]) { stringstream stream; int a,b; stream<<"80"; stream>>a; cout<<"Size of stream = "<<stream.str().length()<<endl; stream.clear(); stream.str(""); cout<<"Size of stream = "<<stream.str().length()<<endl; stream<<"90"; stream>>b; cout<<"Size of stream = "<<stream.str().length()<<endl; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
運行結果:

stringstream默認空格會直接分詞!
題目:輸入的第一行有一個數字 N 代表接下來有 N 行數字,每一行數字里有不固定個數的整數,打印每一行的總和。
輸入:
3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999
輸出:
6
251
4995
string s; stringstream ss; int n, i, sum, a; cin >> n; getline(cin, s); // 換行讀取 for (i=0; i<n; i++) { getline(cin, s); ss.clear(); ss.str(s); sum=0; while (1) { ss >> a; if ( ss.fail() )
break; sum+=a; } cout << sum << endl; }
