2013年6月29日土曜日

開発環境

プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第1章(やさしい入門)、1.10(外部変数と通用範囲)の演習1-23を解いてみる。

その他参考書籍

演習 1-23.

コード

sample.c

#include <stdio.h>

void skip_coment(int);
void in_comment(void);
void quote(int c);

int main()
{
    int c;
    
    while ((c = getchar()) != EOF) {
        skip_coment(c);
    }
    printf("/* 偽コメント */\n");
    return 0;
}

/* コメントを飛ばす */
void skip_coment(int c)
{
    int d;
    if (c == '/') {
        if ((d = getchar()) == '*') {
            in_comment();
        } else if (d == '/') {
            putchar(d);
            skip_coment(d);
        } else {
            putchar(c);
            putchar(d);
        }
    } else if (c == '\'' || c == '"') {
        putchar(c);
        quote(c);
        putchar(c);
    } else {
        putchar(c);
    }
}

/*
 * コメントの終わりを探す
 */
void in_comment(void)
{
    int c, d;
    
    c = getchar();
    d = getchar();
    while (c != '*' || d != '/') {
        c = d;
        d = getchar();
    }
}

/*
 * シングル/ダブルクォートで囲まれた終わりを探す
 */
void quote(int c)
{
    int d;
    
    while ((d = getchar()) != c) {
        putchar(d);
        if (d == '\\') {
            putchar(getchar());
        }
    }
}

入出力結果(Terminal)

$ ./a.out < sample.c
#include <stdio.h>

void skip_coment(int);
void in_comment(void);
void quote(int c);

int main()
{
    int c;
    
    while ((c = getchar()) != EOF) {
        skip_coment(c);
    }
    printf("/* 偽コメント */\n");
    return 0;
}


void skip_coment(int c)
{
    int d;
    if (c == '/') {
        if ((d = getchar()) == '*') {
            in_comment();
        } else if (d == '/') {
            putchar(d);
            skip_coment(d);
        } else {
            putchar(c);
            putchar(d);
        }
    } else if (c == '\'' || c == '"') {
        putchar(c);
        quote(c);
        putchar(c);
    } else {
        putchar(c);
    }
}


void in_comment(void)
{
    int c, d;
    
    c = getchar();
    d = getchar();
    while (c != '*' || d != '/') {
        c = d;
        d = getchar();
    }
}


void quote(int c)
{
    int d;
    
    while ((d = getchar()) != c) {
        putchar(d);
        if (d == '\\') {
            putchar(getchar());
        }
    }
}
/* 偽コメント */
$

0 コメント:

コメントを投稿