Reputation: 20058
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
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
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:
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 resultboost::lexical_cast
. That's a pretty elegant way to handle the problem and would most likely be my preferred oneUpvotes: 1
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
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
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
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