Sorry if this is a super easy question, but I am very new to C. I want to be able to cast char*s into doubles and ints and can't seem to find an explanation as to how.
Edit: I am reading in user input, which is a char*. Half of the input I want to convert from, say, "23" to 23 and half from, for example, "23.4" to 23.4.
There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()
Description. The C library function double strtod(const char *str, char **endptr) converts the string pointed to by the argument str to a floating-point number (type double). If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.
When casting character pointer to integer pointer, integer pointer holds some weird value, no where reasonably related to char or char ascii code. But while printing casted variable with '%c', it prints correct char value. Printing with '%d' gives some unknown numbers.
You can cast a char*
like this:
char *c = "123.45";
int i = (int) c; // cast to int
double d = (double) c; // cast to double
But that will give nonsensical results. It just coerces the pointer to be treated as an integer or double.
I presume what you want is to parse (rather than cast) the text into an int
or double
. Try this:
char *c = "123.45";
int i = atoi(c);
double d = atof(c);
Strictly speaking, you can do this: (int)pointer.
However, you are probably looking for the atoi and atof functions.
atoi is a function that converts a char* pointing to a string containing an integer in decimal to an integer .
atof is likewise for double.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With