C char* to int conversion
How would I go about converting a two-digit number (type char*
) to an int
?
Solution 1:
atoi can do that for you
Example:
char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234
Solution 2:
Use atoi() from <stdlib.h>
http://linux.die.net/man/3/atoi
Or, write your own atoi()
function which will convert char*
to int
int a2i(const char *s)
{
int sign=1;
if(*s == '-'){
sign = -1;
s++;
}
int num=0;
while(*s){
num=((*s)-'0')+num*10;
s++;
}
return num*sign;
}