In this program I'm writing I have the user enter an ID (4 characters long), first two characters are upper case letters and last two are digits with sum less than or equal to ten. In order to do the sum, I'm trying to use atoi function to convert ID[2] and ID[3] to ints. Can I use atoi in this manner? If not any suggestions on how to work around it?
The best way to take a single digit number individually from a string would probably be subtracting the decimal equivalent of '0' from its decimal value.
Ascii numbers in a string have decimal equivalents of 48 ('0') through 57 ('9'). Subtracting '0' (dec 48) from, for example, '5' (dec 53) would yield 5 as a decimal.
1 2
constchar* str = "15212";
int five = str[1] - '0';
The atoi() function needs a character string, so you would have to take the digit you are interested in and turn it into a string, basically by putting it in an array with a null terminator,
1 2 3 4 5
char ID[] = "AB57";
char work[2];
work[0] = ID[2];
work[1] = 0; // null terminator
int num = atoi(work);
though I'd still go along with the previous suggestion and simply do: