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

C++StringStringstream

C++ Problem Overview


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

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

C++ Solutions


Solution 1 - C++

​​​​​​​

yourStringStream.str()

Solution 2 - C++

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

Solution 3 - C++

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.

Solution 4 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick BoltonView Question on Stackoverflow
Solution 1 - C++Tyler McHenryView Answer on Stackoverflow
Solution 2 - C++Emil HView Answer on Stackoverflow
Solution 3 - C++hkBattousaiView Answer on Stackoverflow
Solution 4 - C++Timo GeuschView Answer on Stackoverflow