Character Operations 229
Program 10.11 Converting a String to its Integer Equivalent
// Function to convert a string to an integer
#include <stdio.h>
int strToInt (const char string[])
{
int i, intValue, result = 0;
for ( i = 0; string[i] >= '0' && string[i] <= '9'; ++i )
{
intValue = string[i] - '0';
result = result * 10 + intValue;
}
return result;
}
int main (void)
{
int strToInt (const char string[]);
printf ("%i\n", strToInt("245"));
printf ("%i\n", strToInt("100") + 25);
printf ("%i\n", strToInt("13x5"));
return 0;
}
Program 10.11 Output
245
125
13
The forloop is executed as long as the character contained in string[i]is a digit
character. Each time through the loop, the character contained in string[i]is convert-
ed into its equivalent integer value and is then added into the value of resultmultiplied
by 10.To see how this technique works, consider execution of this loop when the func-
tion is called with the character string "245"as an argument:The first time through the
loop,intValueis assigned the value of string[0] – '0'. Because string[0]contains
the character '2', this results in the value 2 being assigned to intValue. Because the
val ue of resultis 0 the first time through the loop, multiplying it by 10 produces 0,
which is added to intValueand stored back in result.So, by the end of the first pass
through the loop,resultcontains the value 2.