Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ostream into standard string

Tags:

c++

iostream

stl

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

like image 978
Stephen Diehl Avatar asked Aug 18 '10 14:08

Stephen Diehl


People also ask

What is STD Ostream in C++?

The ostream class: This class is responsible for handling output stream. It provides number of function for handling chars, strings and objects such as write, put etc..

Is Ostringstream an Ostream?

ostringstream is used when you need stream stuff into string , whereas ostream is mostly used as a type for a parameter (referenced) when the callee is stream implementation agnostic. And "ostream objects are stream objects used to write and format output as sequences of characters".

How do you declare a Stringstream in C++?

To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.


2 Answers

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(); } 
like image 83
Foo Avatar answered Sep 23 '22 10:09

Foo


     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.

like image 38
James Curran Avatar answered Sep 22 '22 10:09

James Curran