N=1

主にコンピュータ技術関連のことを投稿。 / 投稿は個人の意見であり所属団体の立場を代表するものではありません。

1-20.c

演習 1-20 入力されたタブを、次のタブ・ストップまでのスペースをうめる適当な数のブランク(空白)で置き換えるプログラムdetabを書け。タブ・ストップの位置は、例えばn文字ごとというように固定して考えよ。nは変数にすべきか、記号パラメータにすべきか?

#include <stdio.h>
#define TABSTOP 4

main()
{
        int c, count = 0;

        while ((c = getchar()) != EOF) {
                if (c == '\t') {
                        while ((count++) < TABSTOP) {
                                putchar(' ');
                        }
                        count = 0;
                } else {
                        putchar(c);
                        if (c == '\n' || count >= TABSTOP)
                                count = 0;
                        else {
                                count++;
                        }
                }
        }

        return 0;
}

上のコピペでは行頭全部スペースですが、実際のソースはタブ使って書いてます。
そして下の実際の表示は、わかりやすいようにtrコマンドでスペースを_に置き換えてみました。

$ ./a.out < 1-20.c | tr ' ' _
#include_
#define_TABSTOP_4

main()
{
____int_c,_count_=_0;

____while_((c_=_getchar() )_!=_EOF)_{
________if_(c_==_'\t')_{
____________while_((count++)_<_TABSTOP)_{
________________putchar('_');
____________}
____________count_=_0;
________}_else_{
____________putchar(c);
____________if_(c_==_'\n'_||_count_>=_TABSTOP)
________________count_=_0;
____________else_{
________________count++;
____________}
________}
____}

____return_0;
}