# string to int conversion not using atoi()

• 05-18-2004
linucksrox
string to int conversion not using atoi()
I'm trying to figure out how to convert a string to an int without using atoi(). I'm doing a programming excersise from a book I'm reading, and it says
"Use the character classification functions to prepare an implementation of atoi()." So that means using the ctype.h functions...
But short of creating an entire algorithm to find the number of digits of the int, then multiplying the 1st digit by 10^n, then add the second digit times 10^n-1 and so on. Is that what I need to do? Or is there a way simpler process to do this? Maybe someone could just explain how the atoi() function does its thing, I couldn't find the source code anywhere through google and just opening up stdlib.h didn't make much sense to me...
• 05-19-2004
Thantos
Basically it works like this:
Code:

```string: 150 sum: 0 pointer to the character 1 begin loop   sum = sum * 10   sum = sum + the number pointer is pointing to   move pointer to next character   if we aren't pointing to the end of the string, repeat the loop end loop sum now holds the value```
broken down by example (loop unrolled)
Code:

```string = 125 sum = 0 sum = sum * 10 // 0 * 10 is still 0 sum = sum + 1  // Now sum is 1 sum = sum * 10 // Now sum is 10 sum = sum + 2  // Now sum is 12 sum = sum * 10 // Now sum is 120 sum = sum + 5  //  Now sum is 125```
• 05-19-2004
linucksrox
Thanks Thantos, I understand it and that's definitely a much better way than what I was about to do. That way I don't have to check the number of digits and use that as an exponent to 10 to multiply each digit, if you catch my drift. Now all I gotta do is make the function read in the string and create another string that is only an int, and go from there.