演習 3-6
無職の間にK&Rを再読。演習問題の解答をさらす。解く順番は適当。
演習 3-6
二つでなく三つの引数を受け付ける形の itoa プログラムを書け。第3番目の引数は最小のフィールド幅を指定するものである。幅を確保するために必要なら変換された数には左にブランクをつめなければならない。
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.
やばい、演習の解答ストックが尽きてきた。しかも先の問題がなかなか解けない。
#include <stdio.h> #include <string.h> int abs(int n); void reverse(char s[]); /* Answer */ void itoa(int n, char s[], int len) { int i, sign; sign = n; i = 0; do { s[i++] = abs(n % 10) + '0'; } while ((n /= 10) != 0); if (sign < 0) s[i++] = '-'; while (i < len) s[i++] = ' '; s[i] = '\0'; reverse(s); } int abs(int n) { return n < 0 ? -n : n; } 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; } } int main(void) { int n; char s[100]; n = -12345; itoa(n, s, 3); printf("%d [%s]\n", n, s); itoa(n, s, 10); printf("%d [%s]\n", n, s); return 0; }