Exercise 3-6

Write a version of itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough.

Adding on to itoa from Exercise 3-4, once we finish appending characters to our string, while i (which is equal to the length of the string minus one) is less than the minimum field width provided, we repeatedly add whitespace and increment i until the condition is no longer satisfied. Note that we are appending blanks to the end of the string, so when it is reversed, they will be on the left.

    /* itoa:  convert n to characters in s */
    void itoa(int n, char s[], int min)
    {
        int i, sign;
    
        sign = (n >= 0) ? 1 : -1;
        i = 0;
        do {       /* generate digits in reverse order */
            s[i++] = n % 10 * sign + '0';   /* get next digit */
        } while (sign * (n /= 10) > 0);     /* delete it */
        if (sign == -1)
            s[i++] = '-';
        for (; i < min; ++i)
            s[i] = ' ';
        s[i] = '\0';
        reverse(s);
    }