10

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.

DazedAndConfused
  • 771
  • 3
  • 8
  • 19
  • Do you mean cast or convert? In other words do you want to convert `"42"` into the number `42` or treat the memory the `char*` points to as an `int` – JaredPar Mar 07 '12 at 23:46
  • Working code on how to use `strtol()` can be found [here](http://stackoverflow.com/a/2729534/50049), I'm closing this out as too localized since you weren't quite sure of the problem you were facing. – Tim Post Mar 08 '12 at 06:39

2 Answers2

25

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);
Graham Borland
  • 60,055
  • 21
  • 138
  • 179
2

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.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • 3
    The `strtol()` family of functions is recommended over `atoi()`, if only because `atoi()` returns the same thing when it fails and when it successfully parses `0`. – Pascal Cuoq Mar 07 '12 at 23:54
  • 2
    `atoi()` does no error checking whatsoever. `strtol()` does handle errors, sets meaningful errnos and even copies garbage found in input for later inspection. – Tim Post Mar 08 '12 at 06:42
  • True, but atoi is closer to the equivalent of cast string to integer in higher level languages. – Joshua Mar 08 '12 at 17:05