我想要清理和重用一个ostringstream (和底层缓冲区),这样我的应用程序就不需要做太多的分配。如何将对象重置为其初始状态?
发布于 2009-03-08 21:08:39
在过去,我使用了一系列的clear和str:
// clear, because eof or other bits may be still set.
s.clear();
s.str("");
它已经完成了输入和输出字符串流的工作。或者,您可以手动清除,然后在开始处查找适当的序列:
s.clear();
s.seekp(0); // for outputs: seek put ptr to start
s.seekg(0); // for inputs: seek get ptr to start
这将防止str
通过覆盖当前输出缓冲区中的任何内容来进行某些重新分配。结果如下所示:
std::ostringstream s;
s << "hello";
s.seekp(0);
s << "b";
assert(s.str() == "bello");
如果你想使用c函数的字符串,你可以使用std::ends
,把一个终止null放在下面:
std::ostringstream s;
s << "hello";
s.seekp(0);
s << "b" << std::ends;
assert(s.str().size() == 5 && std::strlen(s.str().data()) == 1);
std::ends
是废弃的std::strstream
的遗留物,它能够直接写入堆栈上分配的字符数组。您必须手动插入一个终止null。然而,我认为std::ends
并没有被弃用,因为在上面的例子中它仍然很有用。
发布于 2009-03-08 21:01:43
似乎ostr.str("")
调用做到了这一点。
发布于 2011-11-03 08:31:56
如果您要清除缓冲区,使其在第一次使用之前被清除,则需要首先使用MSVC向缓冲区添加一些内容。
struct Foo {
std::ostringstream d_str;
Foo() {
d_str << std::ends; // Add this
}
void StrFunc(const char *);
template<class T>
inline void StrIt(const T &value) {
d_str.clear();
d_str.seekp(0); // Or else you'll get an error with this seek
d_str << value << std::ends;
StrFunc(d_str.str().c_str()); // And your string will be empty
}
};
https://stackoverflow.com/questions/624260
复制相似问题