Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
bitmask Avatar asked Jun 01 '12 11:06

bitmask


People also ask

What is std :: Ostringstream?

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 .

What is the difference between Stringstream and Istringstream?

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.


2 Answers

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.

like image 179
Shahbaz Avatar answered Oct 26 '22 22:10

Shahbaz


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.

like image 36
Jonathan Wakely Avatar answered Oct 27 '22 00:10

Jonathan Wakely