Exercise 3.6 - itoa with field width

Question

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.

/* a function of itoa, which accepts the third argument as the width of the
number. the string representation is padded with blanks in the left to get the
required width */

#include <stdio.h>
#include <string.h>

#define MAXLIMIT 100

void itoa(int n, char s[], int w);
void reverse(char s[]);

int main(void) {
    int number, width;
    char str[MAXLIMIT];

    number = -343565;
    width = 10;

    itoa(number, str, width);

    printf("%s", str);

    return 0;
}

void itoa(int n, char s[], int w) {
    int i, sign;

    if ((sign = n) < 0)
        n = -n;
    i = 0;

    do {
        s[i++] = (n % 10) + '0';

    } while ((n /= 10) > 0);

    if (sign < 0)
        s[i++] = '-';

    while (i < w)
        s[i++] = ' ';

    s[i] = '\0';

    reverse(s);
}

void reverse(char s[]) {
    int i, j, c;

    for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
        c = s[i], s[i] = s[j], s[j] = c;
}

Explanation

Note: For negative numbers the negative sign is written close to the number instead of before the padded width. This is itoa conversion with padding. We specify the width of the number we want in w and as before, we proceed with itoa, wherein extract the unit digit (n % 10), convert it to character and store it in a character array. If it were a negative number we store the sign too. We keep track of number of digits in the number in a variable, i and for the remaining digits, for i < w, we append the space character “ “.

We reverse the string thus constructed for our result.

Visualize It

Run It