Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you cast a char* to an int or a double in C [closed]

Tags:

c

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.

like image 533
DazedAndConfused Avatar asked Mar 07 '12 23:03

DazedAndConfused


People also ask

Can you cast a char to an int in c?

There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()

How do you turn a char into a double?

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.

What happens when you cast a char pointer to an int pointer?

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.


2 Answers

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);
like image 87
Graham Borland Avatar answered Oct 14 '22 00:10

Graham Borland


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.

like image 25
Joshua Avatar answered Oct 14 '22 00:10

Joshua