Writing stringstream contents into ofstream

I'm currently using std::ofstream as follows:

std::ofstream outFile;
outFile.open(output_file);

Then I attempt to pass a std::stringstream object to outFile as follows:

GetHolesResults(..., std::ofstream &outFile){
  float x = 1234;
  std::stringstream ss;
  ss << x << std::endl;
  outFile << ss;
}

Now my outFile contains nothing but garbage: "0012E708" repeated all over.

In GetHolesResults I can write

outFile << "Foo" << std:endl; 

and it will output correctly in outFile.

Any suggestion on what I'm doing wrong?

Answers


You can do this, which doesn't need to create the string. It makes the output stream read out the contents of the stream on the right side (usable with any streams).

outFile << ss.rdbuf();

If you are using std::ostringstream and wondering why nothing get written with ss.rdbuf() then use .str() function.

outFile << oStream.str();

When passing a stringstream rdbuf to a stream newlines are not translated. The input text can contain \n so find replace won't work. The old code wrote to an fstream and switching it to a stringstream losses the endl translation.


I'd rather write ss.str(); instead of ss.rdbuf(); (and use a stringstream).

If you use ss.rdbuf() the format-flags of outFile will be reset rendering your code non-reusable. I.e., the caller of GetHolesResults(..., std::ofstream &outFile) might want to write something like this to display the result in a table:

outFile << std::setw(12) << GetHolesResults ...

...and wonder why the width is ignored.


Need Your Help

Pass struct by reference in C

c struct

Is this code correct? It runs as expected, but is this code correctly using the pointers and dot notation for the struct?

C++ inherited class has member of same name

c++ class base

In C++ you can put a member in a base class and a member with the same name in the inherited class.