Home > Backend Development > C++ > How to Reuse ostringstreams?

How to Reuse ostringstreams?

Linda Hamilton
Release: 2024-10-24 04:34:02
Original
981 people have browsed it

How to Reuse ostringstreams?

How to reuse ostringstream?

To avoid applications allocating memory frequently, you may want to clear and reuse ostringstream (and its underlying buffer). To reset an object to its initial state, follow these steps:

Using clear and str

In the past, sequences of clear and str were used to achieve this :

<code class="cpp">// 清除,因为 eof 或其他位可能仍然设置。
s.clear();
s.str("");</code>
Copy after login

This works for both input and output stringstreams.

Manually clear and find

Alternatively, you can manually clear and then start with the appropriate sequence lookup:

<code class="cpp">s.clear();
s.seekp(0); // 对于输出:将放置指针指向开头
s.seekg(0); // 对于输入:将获取指针指向开头</code>
Copy after login

This will prevent str Perform some reallocation, instead overwriting whatever is currently in the output buffer. The result is as follows:

<code class="cpp">std::ostringstream s;
s << "hello";
s.seekp(0);
s << "b";
assert(s.str() == "bello");</code>
Copy after login

For c-functions use std::ends

If you want to use that string for c-functions, you can use std::ends ends, putting a terminating null, like this:

<code class="cpp">std::ostringstream s;
s << "hello";
s.seekp(0);
s << "b" << std::ends;
assert(s.str().size() == 5 && std::strlen(s.str().data()) == 1);</code>
Copy after login

std::ends is a remnant of the deprecated std::strstream, which is able to write directly to what you allocated on the stack char array. You must manually insert a terminating null. However, std::ends is not deprecated, I think because it is still useful in the above situation.

The above is the detailed content of How to Reuse ostringstreams?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template