atoi function

Feb 8, 2014 at 3:48pm
I am looking at an implemntation of the atoi function below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int atoi(char s[])
{

    int i, n;



    n = 0;


    for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)



        n = 10 * n + (s[i] – '0');

    return n;
}


Anyone know the purpose of this line right here "10 * n". Why are we multipling n by 10?
Feb 8, 2014 at 4:17pm
Suppose your s contains '1','2','3'. Before the loop, n=0. At i=0, s[i]-'0' is 1, so n=1. At i=1, s[i]-'0'=2, 10*n=10, so n will become 12. In the next iteration, n=12*10+3=123
Feb 8, 2014 at 5:14pm
Maybe, I am not following what the atoi function is supposed to do. I thought it gives the integer equivalent of an ascii character. So when we have a character '3', shouldn't it return 51 and not 123?
http://www.asciitable.com/
Feb 8, 2014 at 5:17pm
atoi takes the string representation of a number and converts it to that number.
So if you call atoi on the string "123", it will return the int value 123.

If you want to convert a character to its ASCII value, you just need to cast it to an int (or otherwise): static_cast<int>('3') // Gives you 51 .
Feb 8, 2014 at 5:39pm
I see, for each iteration, we increase by power of 10, since we are using the decimal system, which is base-10. So first iteration is one's place. Second iteration is ten's place. Third iteration is in hundred's place. And so forth.
Topic archived. No new replies allowed.