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*
?
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..
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".
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”.
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(); }
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.
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