bitmask
bitmask

Reputation: 34626

What should I use instead of std::ostrstream?

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?

Upvotes: 11

Views: 8937

Answers (5)

Agnel Kurian
Agnel Kurian

Reputation: 59466

With C++20 you can use std::format

Upvotes: 1

Shahbaz
Shahbaz

Reputation: 47533

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.

Upvotes: 19

betabandido
betabandido

Reputation: 19694

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.

Upvotes: 0

Jonathan Wakely
Jonathan Wakely

Reputation: 171303

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.

Upvotes: 3

robert
robert

Reputation: 34398

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.

Upvotes: 1

Related Questions