演習3-6 K&R プログラミング言語C

演習3-6

文字配列に文字を入れる毎に幅 w の値をデクリメントしてゆき、最後に w の数だけスペースを入れる。

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

#define MAX 1024

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

int main(int argc, char *argv[])
{
    char str1[MAX];
    char str2[MAX];
    int n;

    n = 124;
    itoa(n, str1, 5);
    itoa(n, str2, 8);
    printf("%s%s\n", str1, str2);

    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';
        w--;
    } while ((n /= 10) > 0);
    if (sign < 0) {
        s[i++] = '-';
        w--;
    }
    for (; w > 0; i++, w--) {
        s[i] = ' ';
    }

    s[i] = '
#include <stdio.h>
#include <string.h>

#define MAX 1024

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

int main(int argc, char *argv[])
{
    char str1[MAX];
    char str2[MAX];
    int n;

    n = 124;
    itoa(n, str1, 5);
    itoa(n, str2, 8);
    printf("%s%s\n", str1, str2);

    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';
        w--;
    } while ((n /= 10) > 0);
    if (sign < 0) {
        s[i++] = '-';
        w--;
    }
    for (; w > 0; i++, w--) {
        s[i] = ' ';
    }

    s[i] = '\0';
    reverse(s);
}

/* 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;
    }
}
'
; reverse(s); } /* 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; } }

実行結果

$ ./ex3-6
  124     124
プログラミング言語C 第2版 ANSI規格準拠
B.W. カーニハン D.M. リッチー
共立出版
売り上げランキング: 9726
«
»