今天在用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; }
運行結果:
int變量b預期的到的結果應該是90,但是程序運行的結果卻是-858993460這樣一個數據,顯然是哪里錯了。
於是,google一番之后,原因是,stringstream重復使用時,因為沒有清空導致的問題。看到一種解決方案:再次使用前,使用stringstream.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();// stream<<"90"; stream>>b; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
運行結果:
果然,我們得到預期的結果了。
但是,stringstream.clear()是什么呢?
void clear ( iostate state = goodbit );
Set error state flags
Sets a new value for the error control state.
All the bits in the control state are replaced by the new ones; The value existing before the call has no effect.
If the function is called with goodbit as argument (which is the default value) all error flags are cleared.
The current state can be obtained with member function rdstate.
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,每次都增加占用的內存,那么顯然是會有問題的!!!
繼續google之后,stringstream.str()出現了。
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.
可以利用stringstream.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; 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; }
運行結果:
總結一下吧,
void clear ( iostate state = goodbit );//該方法絕非清空stringstream中的內容,而是清空該流的錯誤標記!
void str ( const string & s );//該方法是重新給stringstream賦新值的意思。
於是,我們輕松愉快的解決了問題,么么噠。