开发者

Confused how to convert from a string to double using strtod() in C++

开发者 https://www.devze.com 2023-02-25 01:55 出处:网络
If someon开发者_开发技巧e could explain how to use the function, that would be great.I don\'t understand the parameters.

If someon开发者_开发技巧e could explain how to use the function, that would be great. I don't understand the parameters.

Thanks


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);


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.


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; }
0

精彩评论

暂无评论...
验证码 换一张
取 消