converting int to string

How exactly does this code work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string convertInt(int number)
{
    if (number == 0)
        return "0";
    string temp="";
    string returnvalue="";
    while (number>0)
    {
        temp+=number%10+48;
        number/=10;
    }
    for (int i=0;i<temp.length();i++)
        returnvalue+=temp[temp.length()-i-1];
    return returnvalue;
}


I don't really understand what's going on here.

1
2
3
4
5
    while (number>0)
    {
        temp+=number%10+48;
        number/=10;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    while (number>0) // while the int value number is greater than 0
    {
        temp+=number%10+48; // 48 is the ASCII code for '0'
                            // as '1', '2', '3', ... follow on, adding 1, 2, 3, ...
                            // to 48 give the ASCII code for the chars '1', '2', '3', ...
                            //
                            // number%10 is the remainder when dividing number
                            // by 10, which means the units (which are 0-9)
                            //
                            // temp is a string variable, which has an operator+=(char)
                            // which appends the char to the end of the string
                            //
                            // so temp+=number%10+48; is appending the char corresponding
                            // to the last digit of number to the string temp

        number/=10; // divide number by 10 (as it's integer division, the remainder
                    // is thrown away, so after enough divisons number will be 0
                    // terminating the while loop)
    }


lines 12 and 13 of convertInt() are reversing the string.

Andy
Last edited on
Hey Andy, thanks so much for that explanation. I completely understand what's going on now.
Topic archived. No new replies allowed.