Converting ostream into standard string

C++StlIostream

C++ Problem Overview


I am very new to the C++ STL, so this may be trivial. I have a ostream variable with some text in it.

ostream* pout;
(*pout) << "Some Text";

Is there a way to extract the stream and store it in a string of type char*?

C++ Solutions


Solution 1 - C++

The question was on ostream to string, not ostringstream to string.

For those interested in having the actual question answered (specific to ostream), try this:

void someFunc(std::ostream out)
{
    std::stringstream ss;
    ss << out.rdbuf();
    std::string myString = ss.str();
}

Solution 2 - C++

     std::ostringstream stream;
     stream << "Some Text";
     std::string str =  stream.str();
     const char* chr = str.c_str();

And I explain what's going on in the answer to this question, which I wrote not an hour ago.

Solution 3 - C++

Try std::ostringstream

   std::ostringstream os;
   os<<"Hello world";
   std::string s=os.str();
   const char *p = s.c_str();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStephen DiehlView Question on Stackoverflow
Solution 1 - C++FooView Answer on Stackoverflow
Solution 2 - C++James CurranView Answer on Stackoverflow
Solution 3 - C++Prasoon SauravView Answer on Stackoverflow