Blob
1 /*2 * Exercise 3-6. Write a version of itoa that accepts three arguments instead3 * of two. The third argument is a minimum field width; the converted number4 * must be padded with blanks on the left if necessary to make it wide enough.5 */7 #include <stdio.h>8 #include <stdlib.h>9 #include <limits.h>10 #include <string.h>12 void reverse(char s[]) {13 int c, i, j;14 for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {15 c = s[i];16 s[i] = s[j];17 s[j] = c;18 }19 }21 void itoa(int n, char s[], int width) {22 int i, sign;23 if ((sign = n) < 0)24 n = -n;25 i = 0;26 do {27 s[i++] = n % 10 + '0';28 } while ((n /= 10) > 0);29 if (sign < 0)30 s[i++] = '-';31 while (i < width) {32 s[i++] = ' ';33 }34 s[i] = '\0';35 reverse(s);36 }38 int assert(char *expect, char *actual) {39 printf("Expect: %s\n", expect);40 printf("Actual: %s\n", actual);41 return strcmp(expect, actual);42 }43 int main() {44 char s[100];45 char *t;46 itoa(231523, s, 10);47 assert(" 231523", s);48 itoa(-131523, s, 10);49 assert(" -131523", s);50 itoa(34, s, 0);51 assert("34", s);52 itoa(-21, s, 0);53 assert("-21", s);54 itoa(0, s, 0);55 assert("0", s);56 itoa(0, s, 5);57 assert(" 0", s);58 }