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?
stringstream is constructed with dummy. This copies the entire string's contents into an internal buffer, which is preallocated. dummy is then cleared and then erased, freeing up its allocation.
The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings. By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.
You can't return a stream from a function by value, because that implies you'd have to copy the stream.
Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With