问题
If someone could explain how to use the function, that would be great. I don't understand the parameters.
Thanks
回答1:
First parameter is a pointer to the chars. c_str() gives you that pointer from a string object. Second parameter is optional. It would contain a pointer to the next char after the numerical value in the string. See http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/ for more infos.
string s;
double d;
d = strtod(s.c_str(), NULL);
回答2:
The first argument is a the string you want to convert, the second argument is a reference to a char* that you want to point to the first char after the float in your original string (in case you want to start reading the string after the number). If you do not care about the second argument, you can set it to NULL.
For example, if we have the following variables:
char* foo = "3.14 is the value of pi"
float pi;
char* after;
After pi = strtod(foo, after)
the values are going to be:
foo is "3.14 is the value of pi"
pi is 3.14f
after is " is the value of pi"
Note that both foo and after are pointing to the same array.
回答3:
If you're working in C++, then why don't you use std::stringstream
?
std::stringstream ss("78.987");
double d;
ss >> d;
Or, even better boost::lexical_cast
as:
double d;
try
{
d = boost::lexical_cast<double>("889.978");
}
catch(...) { std::cout << "string was not a double" << std::endl; }
来源:https://stackoverflow.com/questions/5687269/confused-how-to-convert-from-a-string-to-double-using-strtod-in-c