std::string为library type,而int、double为built-in type,两者无法利用(int)或(double)的方式互转,
法1:
使用C的atoi()與atof()。
先利用c_str()轉成C string,再用atoi()與atof()。
int atoi ( const char * str ); //c++ 头文件cstdlib c stdlib.h
Convert string to integer
Parses the C string str interpreting its content as an integral number, which is returned as an int value.
法2:
利用stringstream
这里使用functon template的方式将std::string转int、std::string转double。
#include <iostream> 10#include <sstream> 11#include <string> 12 13template <class T> 14void convertFromString(T &, const std::string &); 15 16int main() { 17 std::string s("123"); 18 19 // Convert std::string to int 20 int i = 0; 21 convertFromString(i,s); 22 std::cout << i << std::endl; 23 24 // Convert std::string to double 25 double d = 0; 26 convertFromString(d,s); 27 std::cout << d << std::endl; 28 29 return 0; 30} 31 32template <class T> 33void convertFromString(T &value, const std::string &s) { 34 std::stringstream ss(s); 35 ss >> value; 36}
http://www.cnblogs.com/oomusou/archive/2006/10/10/525647.html
深入:
http://sealbird.iteye.com/blog/866701