stringstream常用来安全的格式化若干个字符串,数值到一个缓冲区, 而不用担心溢出, 可以用来取代snprintf.
但是很多人都在使用stringstream的时候遇到因为stringstream内部的缓冲区没有正确的清空导致的问题.
那么把stringstream类内部的缓冲区正确的清空方式是什么呢?
stringstream ss;
答案是: ss.str("") 方法.
另外,如果需要把格式化后的字符串通过>>输出到字符串, 必须每次都调用clear()方法!
所以, 保险期间, 每次缓冲区格式化后, 都通过clear(), str("") 两个函数都调用, 把stingstream类复位.
PS1: 网上有一些讨论, 说ss.str("")方法不管用, 而通过 ss.str().clear(); 这可能是c++标准库的实现方法不一致导致. 可以自行看下代码库引用的sstream文件的源码.
在我的linux机器上, /usr/include/c++/4.1.0/sstream, 以及vs2008的实现, 都是和本文是一致的.
PS2: 注意str() 和 str("") 的区别
str() 是返回内部缓冲区的一个copy, str("") 是清空内部缓冲区.
测试程序:
#include <sstream> #include <stdio.h> using namespace std; int main() { stringstream ss; string result; int n=1; ss.clear(); ss<<n; ss>>result; printf("result : %s, str : %s\n", result.c_str(), ss.str().c_str());
n=2; ss.clear(); ss<<n; ss>>result; printf("result : %s, str : %s\n", result.c_str(), ss.str().c_str());
n=3; ss.str(""); ss<<n; ss>>result; printf("result : %s, str : %s\n", result.c_str(), ss.str().c_str());
n=4; ss.clear(); ss.str(""); ss<<n; ss>>result; printf("result : %s, str : %s\n", result.c_str(), ss.str().c_str()); }
测试结果:
result : 1, str : 1
result : 2, str : 12 // 调用了clear(), 没有调用str(""), 结果错误.
result : 2, str : // 调用了 str(""), 没有调用clear(), 结果错误.
result : 4, str : 4 // 调用了 clear()和str(""), 结果正确.
附上str("")和str()的内部实现:
/** * @brief Setting a new buffer. * @param s The string to use as a new sequence. * * Deallocates any previous stored sequence, then copies @a s to * use as a new one. */ void str(const __string_type& __s) { // Cannot use _M_string = __s, since v3 strings are COW. _M_string.assign(__s.data(), __s.size()); _M_stringbuf_init(_M_mode); }
// Get and set: /** * @brief Copying out the string buffer. * @return A copy of one of the underlying sequences. * * "If the buffer is only created in input mode, the underlying * character sequence is equal to the input sequence; otherwise, it * is equal to the output sequence." [27.7.1.2]/1 */ __string_type str() const { __string_type __ret; if (this->pptr()) { // The current egptr() may not be the actual string end. if (this->pptr() > this->egptr()) __ret = __string_type(this->pbase(), this->pptr()); else __ret = __string_type(this->pbase(), this->egptr()); } else __ret = _M_string; return __ret; }