我该如何在C ++中从std :: stringstream
转换为std :: string
?
我需要在字符串流上调用一个方法吗?
我该如何在C ++中从std :: stringstream
转换为std :: string
?
我需要在字符串流上调用一个方法吗?
yourStringStream.str()
std::stringstream::str()
是你要寻找的方法。
使用std::stringstream
:
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::stringstream ss;
ss << NumericValue;
return ss.str();
}
std::stringstream
是一个更通用的工具。你可以使用更专门的类 std::ostringstream
来完成这个特定的任务。
template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
std::ostringstream oss;
oss << NumericValue;
return oss.str();
}
如果你正在使用std::wstring
类型的字符串,那么你应该优先选择使用std::wstringstream
或者std::wostringstream
。
template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
std::wostringstream woss;
woss << NumericValue;
return woss.str();
}
如果你希望字符串的字符类型可以在运行时选择,那么你还应该将其作为模板变量。
template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
std::basic_ostringstream<CharType> oss;
oss << NumericValue;
return oss.str();
}
对于上述所有方法,您必须包含以下两个头文件。
#include <string>
#include <sstream>
NumericValue
也可以作为std::string
或std::wstring
传递,以与分别使用的std::ostringstream
和std::wostringstream
实例一起使用。 NumericValue
不必是数值类型。记忆中,你可以调用stringstream::str()
来获取std::string
类型的值。