Adrian
Adrian

Reputation: 20058

Cast a pointer to char to a double C++

How can i cast a pointer to char to a double ?
I am using command line arguments and one of the argument is a double but in the program is it passed as a char*.
I tried using static_cast and reinterpret_cast but with no effect.

Upvotes: 0

Views: 6000

Answers (7)

ceo
ceo

Reputation: 1148

The atof man page says "The atof() function has been deprecated by strtod() and should not be used in new code."

Upvotes: 0

Timo Geusch
Timo Geusch

Reputation: 24341

You're trying to convert a string (represented by the char *) into a double. This is not something you can do with a regular built in type cast in C++ as all they do is reinterpret the bit pattern that is being referenced by the pointer. Instead you have to parse the command line argument to extract a double value from the string.

As mentioned, you have several options:

  • you can use atof for the conversion, but it's hard to determine if the conversion errored because both a string that can't be converted and one representing 0.0 give you the same result
  • As Fred Larson mentioned, you can use boost::lexical_cast. That's a pretty elegant way to handle the problem and would most likely be my preferred one
  • You can use iostreams to do the conversion
  • You can write the conversion code yourself (just kidding)

Upvotes: 1

Yuri
Yuri

Reputation: 2028

double val = atof(*charpointer)

atof stands for "all to float", (or "array to float"), and does exactly what you want. If it cannot convert the char array, it returns 0.0. See: Man atof

Upvotes: 3

krtek
krtek

Reputation: 26597

If the double comes from the command line, it is actually a real string, you have to convert it to a double, you can't just cast it.

For example, you can use strtod for this task :

double d = strtod (mystr,NULL);

Upvotes: 1

datenwolf
datenwolf

Reputation: 162164

That's not how type conversion in C/C++ works. You must pass the string through a numeric parser manually. E.g.

char *thestring;
double d;
d = atof(thestring);

Upvotes: 1

Fred Larson
Fred Larson

Reputation: 62053

Try Boost lexical_cast.

Upvotes: 3

fredoverflow
fredoverflow

Reputation: 263048

Pure C++ solution:

#include <sstream>

// ...

std::stringstream ss;
ss << your_char_pointer;
ss >> your_double;

Boost solution:

#include <boost/lexical_cast.hpp>

// ...

your_double = boost::lexical_cast<double>(your_char_pointer);

Upvotes: 3

Related Questions