How do I convert from std::stringstream
to std::string
in C++?
Do I need to call a method on the string stream?
How do I convert from std::stringstream
to std::string
in C++?
Do I need to call a method on the string stream?
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 ofstr()
(for example inauto *ptr = out.str().c_str();
) results in a dangling pointer...
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.
From memory, you call stringstream::str() to get the std::string value out.
I would like to add that you must terminate the strstream buffer with '\0' before calling .str() method. Otherwise you will get bad characters when dumping the string.