How would I go about converting a two-digit number (type char*
) to an int
?
We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.
The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.
The strtol library function in C converts a string to a long integer. The function works by ignoring any whitespace at the beginning of the string, converting the next characters into a long integer, and stopping when it comes across the first non-integer character.
atoi can do that for you
Example:
char string[] = "1234"; int sum = atoi( string ); printf("Sum = %d\n", sum ); // Outputs: Sum = 1234
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; }
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