How to convert char to integer in C?

Possible duplicates:
How to convert one char to int
Character to an integer in C

Can someone tell me how to convert char to int ?

 char c[]={'1',':','3'}; int i=int(c[0]); printf("%d",i); 

When I try to do this, it gives 49.

+83
c char int
May 15 '09 at 12:49
source share
2 answers

In the old days, when we could assume that most computers used ASCII, we would just do

 int i = c[0] - '0'; 

But these days Unicode is not a good idea. It has never been a good idea if your code should run on a non-ASCII computer.

Edit: Although this looks like a hacker, it is obvious that the standard is working. Thanks @Earwicker.

+141
May 15 '09 at 12:52
source share

The standard atoi() function is likely to do what you want.

A simple example using "atoi":

 #include <unistd.h> int main(int argc, char *argv[]) { int useconds = atoi(argv[1]); usleep(useconds); } 
+35
May 15 '09 at 12:50
source share



All Articles