How to reuse an ostringstream?(如何重用 ostringstream?)
问题描述
我想清除并重用一个 ostringstream(和底层缓冲区),这样我的应用程序就不必进行那么多的分配.如何将对象重置为其初始状态?
I'd like to clear out and reuse an ostringstream (and the underlying buffer) so that my app doesn't have to do as many allocations. How do I reset the object to its initial state?
推荐答案
我以前用过 clear 和 str 的序列:
I've used a sequence of clear and str in the past:
// clear, because eof or other bits may be still set.
s.clear();
s.str("");
这对输入和输出字符串流都完成了.或者,您可以手动清除,然后寻找合适的顺序开始:
Which has done the thing for both input and output stringstreams. Alternatively, you can manually clear, then seek the appropriate sequence to the begin:
s.clear();
s.seekp(0); // for outputs: seek put ptr to start
s.seekg(0); // for inputs: seek get ptr to start
这将通过覆盖当前输出缓冲区中的任何内容来防止 str
进行一些重新分配.结果是这样的:
That will prevent some reallocations done by str
by overwriting whatever is in the output buffer currently instead. Results are like this:
std::ostringstream s;
s << "hello";
s.seekp(0);
s << "b";
assert(s.str() == "bello");
如果你想在 c 函数中使用字符串,你可以使用 std::ends
,像这样放置一个终止空值:
If you want to use the string for c-functions, you can use std::ends
, putting a terminating null like this:
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
的产物,它能够直接写入您在堆栈上分配的字符数组.您必须手动插入终止空值.但是,std::ends
并没有被弃用,我认为因为它在上述情况下仍然很有用.
std::ends
is a relict of the deprecated std::strstream
, which was able to write directly to a char array you allocated on the stack. You had to insert a terminating null manually. However, std::ends
is not deprecated, i think because it's still useful as in the above cases.
这篇关于如何重用 ostringstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何重用 ostringstream?
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01