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

前端 未结 4 1547
囚心锁ツ
囚心锁ツ 2020-12-12 21:50

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

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

相关标签:
4条回答
  • 2020-12-12 22:04

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

    0 讨论(0)
  • 2020-12-12 22:10

    ​​​​​​​

    yourStringStream.str()
    
    0 讨论(0)
  • 2020-12-12 22:15

    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.

    0 讨论(0)
  • 2020-12-12 22:17

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

    0 讨论(0)
提交回复
热议问题