Writing stringstream contents into ofstream

Eric picture Eric · Nov 27, 2008 · Viewed 57.4k times · Source

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?

Answer

Johannes Schaub - litb picture Johannes Schaub - litb · Nov 28, 2008

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();