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; }