c++ clear()在流中時清空所有標記, 在string中時清空字符串.所以ostringstream.clear()不是清空oss,而是清除標記.


 由於C++中的std::string沒有提供類似format這樣的函數,遇到字符串的格式化一般的替代品是用std::ostringstream。但ostringstream有一些方法非常容易用錯:

void clear ( iostate state = goodbit ) 該方法絕非清空ostringstream中的內容,而是清空該流的錯誤標記!非常容易用錯的stringstream - 秒大刀 - 秒大刀的城堡在STL容器里clear方法的含義均為清空容器,但在STL的所有流中clear的含義均為清空錯誤標記!

void str ( const string & s ) 該方法是重新給ostringstream灌新值的意思。比如oss.str("")將會執行真正的oss清空操作,神奇吧?同理 oss.str("Hello")將會使oss中的內容為"Hello"。但注意:oss.str("Hello"); oss << "World";的執行結果將會變成"World"而不是"HelloWorld",這種功能簡直太神奇了,讓我活到老學oss到老啊。

不知道世界上有多少程序員曾經為stringstream而憤怒過……

 


2009-11-25

ostringstream::str簽名為:

string str ( ) const;    // returns a copy of the string object currently associated with the string stream buffer.
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.

項目中經常會用到ostringstream.str()方法,盡量控制不必要的重復調用,這可能會帶來性能問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM