How do I convert from stringstream to string in C++?


Question

How do I convert from std::stringstream to std::string in C++?

Do I need to call a method on the string stream?

1
111
10/13/2017 4:58:25 PM

Accepted Answer

yourStringStream.str()

177
3/19/2009 4:38:00 PM

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon