K&Rを読もう(15) 演習 1-22 テキストの折り返し
K&Rの演習が段々むずかしくなってきたぞぉぉぉぉ。
指定文字数でテキストの折り返しを作る問題。長い単語にも対応しなければならないらしい。
#include <stdio.h> #include <stdlib.h> #define LINE 40 #define WORDMAX 1024 int main(void) { int c; int i = 0,j; int len = 0; char word[WORDMAX]; while ((c = getchar()) != EOF) { i++; /* 行の文字数カウンタ*/ word[len++] = c; /* 単語バッファ */ if (c == ' ' || c == '\n') { if (i > LINE) { putchar('\n'); i = len; } word[len] = '\0'; if (len < LINE) printf("%s", word); else { /* 長い単語の折り返し用 */ for (j = 0; word[j] != '\0'; j++, i++) { if (j > 0 && j % (LINE - 1) == 0) { printf("-\n"); i = 0; } putchar(word[j]); } } len = 0; if (c == '\n') i = 0; } } exit(EXIT_SUCCESS); }
長い単語の折り返しがしんどかった。バッファオーバーフローはチェックしてない。
テスト。
% ./ex-1-22 < test.txt The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. LoooooooooooooooooongWord Loooooooooooooooooooooooooooooooooooooo- oooongWord Loooooooooooooooooooooooooooooooooooooo- ooooooooooooooooooooooooooooooooooooooo- oooooooooooooooooongWord
ぜぇぜぇ。