Page 64

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.

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

#define LEN 1000

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

int main()
{
	char s[LEN];

	itoa(-1234, s, 8);

	printf("%s", s);
}

void itoa(int n, char s[], int min)
{
	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++] = '-';
	for (; i <= min; i++) {
		s[i] = ' ';
	}
	s[i] = '\0';
	reverse(s);
}

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

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