Sam
Sam

Reputation: 2347

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

If someone could explain how to use the function, that would be great. I don't understand the parameters.

Thanks

Upvotes: 3

Views: 11608

Answers (3)

Charles Brunet
Charles Brunet

Reputation: 23120

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

Upvotes: 5

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.

Upvotes: 3

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361522

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

Upvotes: 1

Related Questions