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()方法,尽量控制不必要的重复调用,这可能会带来性能问题。

posted @ 2012-03-10 20:41  springbarley  阅读(4441)  评论(0编辑  收藏  举报