課題
Cプログラムから全てのコメントを除去するプログラムを書け。
回答
#include <stdio.h> #include <string.h> typedef unsigned long int u8; /** * @fn Main * @brief * @param * @return * @detail */ int main(void) { int c; char str[1000]; u8 pos_str = 0, pos_start_comment = 0; while ((c = getchar()) != EOF) { // ファイル終端まで str[pos_str] = c; // 入力文字を格納 if (c == '\n') { // 行末なら str[pos_str + 1] = '\0'; // ヌル文字追加 printf("%s", str); // 印字 // 初期化 pos_str = 0; // 格納文字位置 } // 開始判定 if ((str[pos_str - 1] == '/') && // 今回が'/'で (str[pos_str ] == '*')) { // 前回が'*'なら pos_start_comment = pos_str - 1; // コメント開始 } // 終了判定 if ((str[pos_str - 1] == '*') && // 今回が'*'で (str[pos_str ] == '/')) { // 前回が'/'で if (pos_start_comment != 0) { // コメント開始済みなら pos_str = pos_start_comment - 1; // コメント終了 pos_start_comment = 0; // コメント開始位置の初期化 } } pos_str++; // 次の文字へ } }
実行内容
abc/*defg*/j
実行結果
abcj