82

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*?

Stephen Diehl
  • 8,271
  • 5
  • 38
  • 56

3 Answers3

211

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();
}
Kalin
  • 1,691
  • 2
  • 16
  • 22
Foo
  • 2,129
  • 2
  • 12
  • 3
71
     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.

Community
  • 1
  • 1
James Curran
  • 101,701
  • 37
  • 181
  • 258
7

Try std::ostringstream

   std::ostringstream os;
   os<<"Hello world";
   std::string s=os.str();
   const char *p = s.c_str();
Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 1
    The question isn't about `std::ostringstream` but about `std::ostream`. `std::ostream` doesn't have a method `.str()`. – Marc Dirven Jul 15 '21 at 09:26