原文链接:http://dearymz.blog.163.com/blog/static/2056574200912644333989/
由于 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
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() 方法,尽量控制不必要的重复调用,这可能会带来性能问题。