I like to use std::ostrstream
to format text but not print it to stdout but instead write it into an std::string
(by accessing the std::ostrstream::str()
member). Apparently this is deprecated now. So, how am I supposed to write formatted objects to a string, with the same convenience as when writing to a stream?
You could use std::ostringstream
. Similarly, instead of std::istrstream
you should use std::istringstream
. You need to include the <sstream>
header for these classes.
You could also see this question which explains why strstream
was deprecated.
As others have already said, std::ostringstream
is the replacement.
It's more convenient (and safer) than std::ostrstream
because it manages all memory automatically so you don't need to call freeze(false)
to ensure the memory gets freed when you're finished with it.
You should use std::stringstream
. Also, see boost::lexical_cast
.
std::stringstream
supports both <<
and >>
. std::ostringstream
only supports <<
, and std::istringstream
only supports >>
. Often I find it convenient to be able to use both operators.
You can also use boost::format
. Then you can do things like:
int a = 1;
std::string b("foo");
std::string s = boost::str(
boost::format("some text, some vars=%1%, %2%, %1%") % a % b % a);
Then s
would contain "some text, some vars=1, foo, 1"
.
This is, in my opinion, more convenient in some cases than using operator <<
.
As a reference, I also include the format specification.
%.02f
? –
Chromatism © 2022 - 2024 — McMap. All rights reserved.