170

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

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

msc
  • 33,420
  • 29
  • 119
  • 214
Nick Bolton
  • 38,276
  • 70
  • 174
  • 242

4 Answers4

282

​​​​​​​

yourStringStream.str()
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Tyler McHenry
  • 74,820
  • 18
  • 121
  • 166
82

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

gnat
  • 6,213
  • 108
  • 53
  • 73
Emil H
  • 39,840
  • 10
  • 78
  • 97
18

std::stringstream::str() is the method you are looking for.

With std::stringstream:

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::stringstream ss;
    ss << NumericValue;
    return ss.str();
}

std::stringstream is a more generic tool. You can use the more specialized class std::ostringstream for this specific job.

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::ostringstream oss;
    oss << NumericValue;
    return oss.str();
}

If you are working with std::wstring type of strings, you must prefer std::wstringstream or std::wostringstream instead.

template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
    std::wostringstream woss;
    woss << NumericValue;
    return woss.str();
}

if you want the character type of your string could be run-time selectable, you should also make it a template variable.

template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
    std::basic_ostringstream<CharType> oss;
    oss << NumericValue;
    return oss.str();
}

For all the methods above, you must include the following two header files.

#include <string>
#include <sstream>

Note that, the argument NumericValue in the examples above can also be passed as std::string or std::wstring to be used with the std::ostringstream and std::wostringstream instances respectively. It is not necessary for the NumericValue to be a numeric value.

hkBattousai
  • 10,583
  • 18
  • 76
  • 124
11

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

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Timo Geusch
  • 24,095
  • 5
  • 52
  • 70