演習1-22 K&R プログラミング言語C

演習1-22

スペースか改行文字が現われる毎に word バッファに保存している文字列を出力する。
出力の際に最大桁数を超えるかどうかのチェックを行う。
1単語の長さが最大桁数を超える場合は別に処理を行なっている。
長さが見やすいように最初に20個の数字を出力している。

#include <stdio.h>

#define MAXLENGTH 20
#define WORD_SIZE 1024

int main(int argc, char *argv[])
{
    int c, i, j, len, n;
    char word[WORD_SIZE];

    printf("12345678901234567890\n");

    n = MAXLENGTH;

    i = len = 0;
    while ((c = getchar()) != EOF) {
        ++i;
        word[len] = c;
        ++len;

        if (c == ' ' || c == '\n') {
            word[len] = '
#include <stdio.h>

#define MAXLENGTH 20
#define WORD_SIZE 1024

int main(int argc, char *argv[])
{
    int c, i, j, len, n;
    char word[WORD_SIZE];

    printf("12345678901234567890\n");

    n = MAXLENGTH;

    i = len = 0;
    while ((c = getchar()) != EOF) {
        ++i;
        word[len] = c;
        ++len;

        if (c == ' ' || c == '\n') {
            word[len] = '\0';
            if (i > n) {
                putchar('\n');
                i = len;
            }
            if (len < n) {
                printf("%s", word);
            } else {
                for (j = 0; j < len; j++) {
                    if (j > 0 && ((j % n) == 0)) {
                        putchar('-');
                        putchar('\n');
                    }
                    putchar(word[j]);
                }
            }
            len = 0;
            if (c == '\n') {
                i = len;
            }
        }
    }

    return 0;
}
'
; if (i > n) { putchar('\n'); i = len; } if (len < n) { printf("%s", word); } else { for (j = 0; j < len; j++) { if (j > 0 && ((j % n) == 0)) { putchar('-'); putchar('\n'); } putchar(word[j]); } } len = 0; if (c == '\n') { i = len; } } } return 0; }

実行結果

$ cat long.txt
That is the mountain which height is 300m.
This is a pen which color is red.
That is a big mountain which height is 300m.
The Looooooooooooooooooooooooooooooooooong text.
The Looooooooooooooooooooooooooooooooooong text.
The Loooooooooooooooooooooooooooooooooooooooooooooooooooooong text.
The Loooooooooooooooooooooooooooooooooooooooooooooooooooooong text.
$ ./ex1-22 <long.txt
12345678901234567890
That is the 
mountain which 
height is 300m.
This is a pen which 
color is red.
That is a big 
mountain which 
height is 300m.
The 
Looooooooooooooooooo-
oooooooooooooooong 
text.
The 
Looooooooooooooooooo-
oooooooooooooooong 
text.
The 
Looooooooooooooooooo-
oooooooooooooooooooo-
ooooooooooooooong 
text.
The 
Looooooooooooooooooo-
oooooooooooooooooooo-
ooooooooooooooong 
text.
プログラミング言語C 第2版 ANSI規格準拠
B.W. カーニハン D.M. リッチー
共立出版
売り上げランキング: 9726
«
»