数值类型与std::string的相互转换

1.使用std::stringstream:

//将in_value值转换成out_type类型
template<class out_type, class in_value> 
out_type StringTo(const in_value& t)
{
    std::stringstream sstream;
    sstream << t; //向流中传值
    out_type result; //这里存储转换结果
    sstream >> result; //向result中写入值
    return result;
}

2.使用std::ostringstream和std::istringstream

//将各种类型转换为string类型
template <typename T> 
std::string toString(const T& t)
{
    std::ostringstream oss; //创建一个格式化输出流
    oss << t; //把值传递到流中
    return oss.str();
}

//将string类型转换为常用的数值类型
template <class Type> 
Type ConvertTo(const std::string& str)
{
    std::istringstream iss(str);
    Type type;
    iss >> type;
    return type;
}
原文地址:https://www.cnblogs.com/sunwenqi/p/11857244.html