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.
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);
Try Boost lexical_cast.
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
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);
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);
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)
The atof man page says "The atof() function has been deprecated by strtod() and should not be used in new code."
Related
I'm try to compile a simple expression:
char_to_int(tolower(row[y]))
However I'm getting the following errors when trying to compile it:
error: implicit conversion loses integer precision: 'int' to 'char' [-Werror,-Wimplicit-int-conversion]
if (char_to_int(tolower(row[y])) > n
The signature of char_to_int is:
unsigned long char_to_int(char c)
and the type of row[y] is char.
Why am I getting this error and how can I fix it?
From your error information I assume you are using std::tolower from <cctype> (or equivalently, ::tolower from <ctype.h>), not std::tolower from <locale>.
Why you are getting the error is straightforward from your error information: your char_to_int expects a char, but tolower returns an int. This will cause loss of information.
Why does tolower return an int, not just a char? Because it can accept and return EOF, which may fall out of range of any char.
The fix can be straightforward: change your char_to_int to accept int, or do an intermediate step to discard the possible EOF.
std::tolower doesn't actually operate on chars: it operates on ints! Moreover, there is risk of undefined behaviour: if on your machine char is a signed type, then the "negative" characters will correspond to negative integers, which std::tolower is not equipped to deal with.
A way to fix this for your use is to manually cast the types before use:
char_to_int(static_cast<char>(
std::tolower(static_cast<unsigned char>(row[y]))));
... which unfortunately is a bit of a mess, but that's what you have to do.
Alternatively, you may use the locale version of std::tolower, which is templated and will correctly handle char types. You may use it like so:
// std::locale{} is an object representing the default locale
// you may specify a locale precisely if needed; see the above links
char_to_int(std::tolower(row[y], std::locale{}));
tolower returns an int. std::tolower is however a template, and will work correctly for char. In general, if there is a std:: version of any func you are calling, use it! :)
Anyone know how to convert a string to long double? For example lets say we have
string S = "3.236568949"
I want to take what inside the string and convert it to a long double variable x.
Note: In c++11 their exist stold function do so but I'm using c++98 not c++11.
Also I don't need to cout the string with certain precision because I know setprecision function already but what I want is just to convert to long double. In other wards,I need x to equal the exact number inside the string and not an approximated version of the number. Finally I want to tell you that my string contains a valid number.
you can use the C function :
#include <stdlib.h>
int main(){
char* convertme="3.236568949";
double converted=atof(convertme);
return 0;
}
You can use a std::stringstream to convert the string into a long double. The std::stringstream acts just like cin but instead of getting the input from the user you load it into the stream with a std::string. That looks like
std::string data = "3.236568949"
std::stringstream ss(data);
long double ld;
ss >> ld;
Do note that when dealing with floating point numbers you are going to have to deal with imprecision. For more on this see Is floating point math broken?
You can use strtold() function from C99:
long double d = strtold( str.c_str(), nullptr );
to convert std::string to long double. Though floating point representation is approximate so nobody would guarantee that value after conversion is exactly the same is in your string.
Is it not reccomended to convert a string in such way:
string input = "81.312";
double val = atof(input.c_str());
DO NOT use std::atof in C++. That doesn't check for input error.
Use std::stod. That checks for error also and throws exception accordingly.
Also, it takes std::string const & as argument. So you don't have to pass input.c_str(). Just do this:
double value = std::stod(input);
It is not wrong, but more right would be to use boost::lexical_cast.
You should also check if these tools handle NANs and INFs correctly.
I want to convert string to int but the conversion has to consider the prefixes 0x or 0 if any and consider the input as hex or oct respectively. Using istringstream, you need to explicitly specify the base. Is there any way than explicitly coding to check for characters 0x?
Edit:
The conversion should implicitly find the base based on the prefix. Just like int i = 0x123; does.
You can use the std::stoi family of functions from C++11.
You can use C function strtol : http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/
It understands 0x/0 prefices.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to convert a single char into an int
Well, I'm doing a basic program, wich handles some input like:
2+2
So, I need to add 2 + 2.
I did something like:
string mys "2+2";
fir = mys[0];
sec = mys[2];
But now I want to add "fir" to "sec", so I need to convert them to Int.
I tried "int(fir)" but didn't worked.
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
Alright so first a little backround on why what you attempted didn't work. In your example, fir is declared as a string. When you attempted to do int(fir), which is the same as (int)fir, you attempted a c-style cast from a string to an integer. Essentially you will get garbage because a c-style cast in c++ will run through all of the available casts and take the first one that works. At best your going to get the memory value that represents the character 2, which is dependent upon the character encoding your using (UTF-8, ascii etc...). For instance, if fir contained "2", then you might possibly get 0x32 as your integer value (assuming ascii). You should really never use c-style casts, and the only place where it's really safe to use them are conversions between numeric types.
If your given a string like the one in your example, first you should separate the string into the relevant sequences of characters (tokens) using a function like strtok. In this simple example that would be "2", "+" and "2". Once you've done that you can simple call a function such as atoi on the strings you want converted to integers.
Example:
string str = "2";
int i = atoi(str.c_str()); //value of 2
However, this will get slightly more complicated if you want to be able to handle non-integer numbers as well. In that case, your best bet is to separate on the operand (+ - / * etc), and then do a find on the numeric strings for a decimal point. If you find one you can treat it as a double and use the function atof instead of atoi, and if you don't, just stick with atoi.
Have you tried atoi or boost lexical cast?