非常容易用错的 ss

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值