So...I know that the atoi function in the C++ standard library is supposed to convert a string into an integer...how does it work?...(I\'m trying to learn stuff and I was ju
Something like this:
int atoi( const char *c ) {
int value = 0;
int sign = 1;
if( *c == '+' || *c == '-' ) {
if( *c == '-' ) sign = -1;
c++;
}
while ( isdigit( *c ) ) {
value *= 10;
value += (int) (*c-'0');
c++;
}
return value * sign;
}
You loop through the characters in the string as long as they are digits. For each one, add to the counter you're keeping - the value to add is the integer value of the character. This is done by subtracting the ascii value of '0' from the ascii value of the digit in question.
Note that this code doesn't handle overflow. If you pass in "887452834572834928347578423485273" (which won't fit in an int), the result is undefined.