標籤:style blog http color 使用 os
今天在用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賦新值的意思。
於是,我們輕鬆愉快的解決了問題,麼麼噠。