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

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

Do I need to call a method in a string stream?

+83
c ++ string stringstream
Mar 19 '09 at 16:37
source share
5 answers

yourStringStream.str ()

+136
Mar 19 '09 at 16:38
source share

Use . str () - method :

Manages the contents of the underlying string object.

1) Returns a copy of the base string, as if it were calling rdbuf()->str() .

2) Replaces the contents of the base line, as if it were calling rdbuf()->str(new_str) ...

Notes

A copy of the base string returned by str is a temporary object that will be destroyed at the end of the expression, so we directly call c_str() based on the result of str() (for example, in auto *ptr = out.str().c_str(); ) leads to pointer freeze ...

+65
Mar 19 '09 at 16:38
source share

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

+10
Mar 19 '09 at 16:37
source share

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 general tool. You can use the more specialized class std::ostringstream for this specific task.

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

If you are working with the std::wstring string type, you should instead choose std::wstringstream or std::wostringstream .

 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 to be selected at run time, you must 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 of the above methods, you must include the following two header files.

 #include <string> #include <sstream> 

Note that the NumericValue argument in the above examples can also be passed as std::string or std::wstring for use with instances of std::ostringstream and std::wostringstream respectively. NumericValue not required to be a numeric value.

+9
Sep 26 '15 at 20:53 on
source share

I would like to add that before calling the .str () method, you must complete the string buffer with '\ 0'. Otherwise, you will get bad characters when resetting a string.

-2
Feb 24 '14 at 13:15
source share



All Articles