How to combine stringstream << and stringsteam.str() into one single line

std::ostringstream ostr; //output string stream
ostr << 123;
string str = ostr.str();

I know the above will work.

But I would like to combine the above two operation into a single line operation like below

string str = (ostr<<123).ToStr(); // not sure if there is to string function;

Can I clear the ostr before <<123? (of course in single line too)?
Who is Participating?
evilrixConnect With a Mentor Senior Software Engineer (Avast)Commented:
All you have to do is cast the ostream back to a ostringstream

std::string str = static_cast<std::ostringstream &>(ostr << 123).str();

Open in new window

Sorry to say so, but you can't do that. This is because the expression 'ostr << 123' 'returns' a ostream reference, whose interface does not allow any read access to the object's contents.
tommym121Author Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.