在 C 语言的那个时代,我会做一些丑陋和不安全的事情,比如这样:
char sfloat[] = "1.0";
float x;
sscanf (sfloat, "%lf", &x);
在C++中,你可能会像这样做:
include <string>
#include <sstream>
#include <iostream>
template <class T>
bool from_string(T& t,
const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int main()
{
int i;
float f;
if(from_string<int>(i, std::string("ff"), std::hex))
{
std::cout << i << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
if(from_string<float>(f, std::string("123.456"), std::dec))
{
std::cout << f << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
return 0;
}
个人而言,我推荐这个链接:
http://bytes.com/topic/c/answers/137731-convert-string-float
有两种方法。C语言提供了strtod函数,可以在char数组和double之间进行转换:
// C-ish:
input2 = strtod(input.c_str(), NULL);
C++流提供了与各种类型之间的良好转换。要使用字符串和流,请使用stringstream:
// C++ streams:
double input2;
istringstream in(input);
input >> input2;
strtod()
的文档吗? - Greg Hewgill