atoi from cplusplus

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int atoi( char string[] )
{
int sign = 0, // whether the number is negative
result = 0, // result of conversion
position = 0; // position in the string
if ( string[0] == '-' ) // check for minus
{
position++; // skip this character when converting
sign = 1; // the number is negative
}
for ( ; string[position]; position++ ) // for each character in the ( \0 terminated ) string
{
result *= 10; // move the digits by one position
result += string[position] - '0'; // get the number
}
if ( sign ) // if the number was negative
result *= -1; //change the sign
return result; // return the result
}