Nic*_*ton 115 c++ string stringstream
如何从C++ 转换std::stringstream
为std::string
?
我是否需要在字符串流上调用方法?
Emi*_*l H 74
使用.str() - 方法:
管理底层字符串对象的内容.
1)返回基础字符串的副本,就像通过调用一样
rdbuf()->str()
.2)替换底层字符串的内容,就好像通过调用
rdbuf()->str(new_str)
...笔记
由STR返回的基础字符串的副本,将在表达式的结尾被破坏,所以直接调用临时对象
c_str()
上的结果str()
(例如,在auto *ptr = out.str().c_str();
)在悬空指针结果...
hkB*_*sai 13
std::stringstream::str()
是你正在寻找的方法.
同 std::stringstream
:
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::stringstream ss;
ss << NumericValue;
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
std::stringstream
是一个更通用的工具.您可以使用更专业的类std::ostringstream
为此特定作业.
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::ostringstream oss;
oss << NumericValue;
return oss.str();
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用std::wstring
字符串类型,则必须更喜欢std::wstringstream
或std::wostringstream
替代.
template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
std::wostringstream woss;
woss << NumericValue;
return woss.str();
}
Run Code Online (Sandbox Code Playgroud)
如果您希望字符串的字符类型可以在运行时选择,您还应该将其设置为模板变量.
template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
std::basic_ostringstream<CharType> oss;
oss << NumericValue;
return oss.str();
}
Run Code Online (Sandbox Code Playgroud)
对于上述所有方法,您必须包含以下两个头文件.
#include <string>
#include <sstream>
Run Code Online (Sandbox Code Playgroud)
注意,NumericValue
上面示例中的参数也可以分别作为std::string
或与实例std::wstring
一起使用.它不必是数值.std::ostringstream
std::wostringstream
NumericValue