0

I desperately try to write in a ostringstream and then transfert the datas in the istringstream of an other object or in a file.

std::ostringstream oss;
oss << "Hello World";

For the first purpose, I try this :

iss.basic_ios<char>::rdbuf(oss.rdbuf());

But a simple "iss.str()" return nothing at all. (First problem)

Then when I try that :

std::ofstream ofs("test.txt");
ofs << oss.rdbuf();
ofs.close();

Nothing is written in the file test.txt. (Second problem)

Thank you in advance for any explanation of the inside relation between stringstream and streambuf.

fcaillaud
  • 31
  • 7

1 Answers1

1

You're under a misapprehension - doing iss.basic_ios<char>::rdbuf(oss.rdbuf()) only changes the internal pointer of the input string stream to point to the other output string stream's buffer. It has no affect on the content of the internal buffer of iss (i.e there is no transfer of data).

As far as I know the get area of an input string stream can be invalid and unused entirely by its implementation. I don't think there's any way to change that.

David G
  • 94,763
  • 41
  • 167
  • 253
  • So, would it be interesting to set the streambuf cursor to beginning, in the iss ? (even if setting the streambuf while oss continues to use it may be dangerous) – fcaillaud Nov 03 '13 at 10:47
  • Or am I obliged to copy the stringstream as : iss.str(oss.str()) and ofs << oss.str() ?? – fcaillaud Nov 03 '13 at 10:49
  • 1
    @user2928422 I think the latter is the most logical and straightforward solution, so yes: `ofs << oss.str()`. – David G Nov 03 '13 at 12:28