數值類型與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;
}

3.大小寫轉換:

//小寫
std::string& ToLower(std::string& str)
{
    std::transform(str.begin(), str.end(), str.begin(), tolower);
    return str;
}

//大寫
std::string& ToUpper(std::string& str)
{
    std::transform(str.begin(), str.end(), str.begin(), toupper);
    return str;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM