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

Viewed 195670

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

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

4 Answers

​​​​​​​

yourStringStream.str()

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...

From memory, you call stringstream::str() to get the std::string value out.

Related