Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 878
Eric Avatar asked Nov 27 '08 21:11

Eric


People also ask

Does Stringstream allocate?

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.

How does Stringstream work in C++?

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.

Can you return a Stringstream?

You can't return a stream from a function by value, because that implies you'd have to copy the stream.

What is the difference between string and Stringstream?

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.


2 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(); 
like image 178
Johannes Schaub - litb Avatar answered Sep 19 '22 03:09

Johannes Schaub - litb


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

outFile << oStream.str(); 
like image 44
Digital_Reality Avatar answered Sep 21 '22 03:09

Digital_Reality