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?
std::ostringstreamOutput stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str .
A stringstream is an iostream object that uses a std::string as a backing store. An ostringstream writes to a std::string . An istringstream reads from a std::string . You read & write from & to an istringstream or ostringstream using << and >> , just like any other iostream object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With