字符串处理 | 与基本类型的转换
1. 基本类型转换成 string。
/* stringstream */
1 template<class T> 2 void to_string(string &result, T &target) 3 { 4 ostringstream oss; 5 oss << target; 6 result = oss.str(); 7 }
/* atoi */
a = atoi(str.c_str()); // 高效
2. string 转换成基本类型
1 template<class T> 2 T convert(const string &target) 3 { 4 stringstream ss; 5 ss << target; 6 T res; 7 ss >> res; 8 return res; 9 }
C 的 sscanf(效率高了很多):
1 int test(const string &target) 2 { 3 int res; 4 sscanf(target.c_str(), "%d", &res); 5 return res; 6 }