Writing stringstream contents into ofstream
Solution 1
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();
Solution 2
If you are using std::ostringstream
and wondering why nothing get written with ss.rdbuf()
then use .str()
function.
outFile << oStream.str();
Solution 3
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.
Solution 4
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.
Comments
-
Eric over 3 years
I'm currently using
std::ofstream
as follows:std::ofstream outFile; outFile.open(output_file);
Then I attempt to pass a
std::stringstream
object tooutFile
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 writeoutFile << "Foo" << std:endl;
and it will output correctly in
outFile
.Any suggestion on what I'm doing wrong?
-
Alex Bitek almost 11 yearsThis should be a comment not an answer because you haven't told how to write a std::stringstream to a std::ofstream
-
Javi about 9 yearsI'm curious: why this solution works with
std::stringstream
but not withstd::ostringstream
? In the second case I am getting an empty file. -
abcd over 8 yearsyour answer led me to the following realization: to get a
char
array fromss
, you can doss.str().c_str()
. (just posting here for the benefit of newbies who stumble on this in the future.) -
Nasir over 8 years@Digital_Reality, thanks! nothing was getting written when i used rdbuff. What is the reason for this?
-
S.R over 6 years@JaviV because you can only write to
std::oANYSTREAM
and only read fromstd::iANYSTREAM
. There will be no sense foroutput_stream
if it would have alsoread
operations. If you need both just usestd::ANYSTREAM
and you are home :)