Method 1: 使用C的atoi()和atof()。
先利用c_str()转成C string,再用atoi()与atof()。
#include
#include
#include
using namespace std;
int main() {
string s = "123";
double n = atof(s.c_str());
//int n = atoi(s.c_str());
cout << n << endl;
}
Method 2:
利用stringstream 这里使用functon template的方式将std::string转int、std::string转double。
stringstream_to_double.cpp / C++
#include
#include
#include
template
void convertFromString(T &, const std::string &);
int main() {
std::string s("123");
// Convert std::string to int
int i = 0;
convertFromString(i,s);
std::cout << i << std::endl;
// Convert std::string to double
double d = 0;
convertFromString(d,s);
std::cout << d << std::endl;
return 0;
}
template void convertFromString(T &value, const std::string &s) { std::stringstream ss(s); ss >> value; }