由於C++中的std::string沒有提供類似format這樣的函數,遇到字符串的格式化一般的替代品是用std::ostringstream。但ostringstream有一些方法非常容易用錯:
void clear ( iostate state = goodbit ) 該方法絕非清空ostringstream中的內容,而是清空該流的錯誤標記!在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
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()方法,盡量控制不必要的重復調用,這可能會帶來性能問題。