Converting ostream into standard string
106,106
Solution 1
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 2
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 3
std::ostringstream os;
os<<"Hello world";
std::string s=os.str();
const char *p = s.c_str();
Author by
Stephen Diehl
I work with Haskell, functional compilers, and type systems. I'm also on Twitter.
Updated on July 22, 2022Comments
-
Stephen Diehl almost 2 years
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 almost 14 yearsI get the following error message: 'struct std::basic_ostream<char, std::char_traits<char> >' has no member named 'str'
-
Prasoon Saurav almost 14 yearsInclude the necessary headers .
#include <string>
and#include <sstream>
-
Vanuan about 12 yearsIt's not ostream. It is ostringstream
-
ArtOfWarfare over 11 yearsNote that ostringstream << int seems to return a basic_ostream but won't change the type of the lhs? Thus having something like
oss << value; return oss.str();
will compile whilereturn (oss << value).str();
will not. -
moodboom over 10 yearsI'll give you points for being a hothead. Alright.. and for the right answer, heh.
-
Matthew James Briggs almost 10 yearsThis is the correct answer. The answer above, marked as correct, does NOT answer the question.
-
Danny about 7 yearsThis doesn't answer the question, which was "convert ostream to std:string"
-
James Curran about 7 years@Danny It answers the question stated in the text of the message, not the (different) question asked in the title.
-
Danny about 7 yearsWeird. From what I see, neither the title nor text of the question contain the word "ostringstream", while your answer does not contain the word "ostream".
-
Brandon almost 5 yearsThe parameter should be
std::ostream& out
becausestd::ostream
isn't copyable. -
Marc Dirven almost 3 yearsThis doesn't answer the question. It's regarding a
ostream
, notostringstream
. -
Marc Dirven almost 3 yearsThe question isn't about
std::ostringstream
but aboutstd::ostream
.std::ostream
doesn't have a method.str()
.