0

To write data from ostringstream to a ofstream, I have to write something like this:

std::ostringstream ss;
myFile<<ss.str();

on the other hand, if I use the stringstream I can access directly the buffer:

std::stringstream ss;
myFile<<ss.rdbuf();

The problem is that ostringstream::str() makes a copy of the string which is kind of bad because in my program there are very huge strings, so stringstream should be better because I can access directly the buffer for reading. And people here say that we should use ostringstream over the stringstream if we deal only with output operations. I can't simply use a string because I am inserting various type of data. So could someone give me an advice on how to deal with this?

Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
Silencer
  • 1,602
  • 4
  • 17
  • 27
  • 2
    Is there any reason why you can't skip the stringstream altogether and send the output directly to the file? – brettwhiteman Jul 15 '15 at 09:32
  • By writing each bit of data directly into the file, the processing time for the same file has increased a bit, so I was trying to make my app as fast as I can. I have found that inserting medium sized chunks of data works best, I am not really sure why. – Silencer Jul 15 '15 at 09:55
  • Stupid question maybe: Are we sure that the `streambuf` at `.rdbuf` is correct? That it contains nothing more and nothing less than the entire contents that have been written to the `stringstream` so far? Does buffering have an effect? Nobody would expect `cout.rdbuf()` to remember everything that has been written to `cout` so far in the program? – Aaron McDaid Jul 15 '15 at 09:59
  • 2
    @AaronMcDaid That's why he needs an `iostream`-derived class instead of an `ostream`, which would be more like `cout`. It is true, though, that different kinds of streams behave differently when mixing read and write operations. To be generic and support files etc, it would be better to explicitly call `ss.seekg` to go back to the beginning. – Potatoswatter Jul 15 '15 at 10:05

2 Answers2

3

people here say that we should use ostringstream over the stringstream if we deal only with output operations

The main reason for using the more specific ostringstream is to make your intentions clear and avoid mistakes. In this case stringstream is needed to prevent copying a potentially large string, so just use it (carefully).

brettwhiteman
  • 4,210
  • 2
  • 29
  • 38
3

ostringstream is intended for cases where data goes into the stream and never comes out. (Except, of course, for the std::string object that you actually want.)

stringstream is intended for uses where reading and writing both occur. << rdbuf() is a way of reading from the stream, so stringstream is completely appropriate.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421