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 to make it wide enough.

#define   abs(x)    ((x)  < 0 ? -(x) : (x))

/* itoa: convert n to characters in s, w characters wide */
void itoa(int n, char s[], int w){
     int i, sign;
     void reverse(char s[]);

    sign = n;  /*record sign */
    i = 0;
    do{
      s[i++] = abs(n % 10) + '0'; /* get next digit */
    }while((n /= 10) != 10);  /*delete it */
    if (sign < 0)
        s[i++] = '-';
    while(i < w)
       s[i++] = ' ';      /* pad with blanks */
    s[i] = '\0';
    reverse(s);
}

Leave a comment