登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

秒大刀 博客

好好学习 天天向上

 
 
 

日志

 
 
 
 

非常容易用错的stringstream  

2009-02-26 16:43:33|  分类: C/C++ |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

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

  评论这张
 
阅读(4067)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018