如果有人可以解释如何使用该功能,那就太好了。我不明白参数。
谢谢
第一个参数是指向字符的指针。c_str() 为您提供来自字符串对象的指针。第二个参数是可选的。它将在字符串中的数值之后包含一个指向下一个字符的指针。有关更多信息,请参阅http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/。
string s;
double d;
d = strtod(s.c_str(), NULL);
第一个参数是要转换的字符串,第二个参数是对 char* 的引用,它要指向原始字符串中浮点数之后的第一个字符(如果您想在数字)。如果您不关心第二个参数,可以将其设置为 NULL。
例如,如果我们有以下变量:
char* foo = "3.14 is the value of pi"
float pi;
char* after;
之后pi = strtod(foo, after)
的值将是:
foo is "3.14 is the value of pi"
pi is 3.14f
after is " is the value of pi"
请注意, foo 和 after 都指向同一个数组。
如果你在 C++ 中工作,那你为什么不使用std::stringstream
?
std::stringstream ss("78.987");
double d;
ss >> d;
或者,甚至更好boost::lexical_cast
:
double d;
try
{
d = boost::lexical_cast<double>("889.978");
}
catch(...) { std::cout << "string was not a double" << std::endl; }