summaryrefslogtreecommitdiffstats
path: root/1/23.c
blob: 2a563cd195d6bd56b9ea366dff864d2594f08f14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>

#define NONE 0
#define SINGLLC 1
#define MULTILC 2
#define MAXLEN 1000

/* removes comments from a c program */
int main(int argc, char *argv[]) {
  int prev, curr, i, comment;
  char s[MAXLEN];

  i = prev = 0;
  comment = NONE;

  while (i < MAXLEN - 1 && (curr = getchar()) != EOF) {
    if (!comment) {
      if (curr == '/' && prev == '/') {
        comment = SINGLLC;
        i--;
      } else if (curr == '*' && prev == '/') {
        comment = MULTILC;
        i--;
      } else {
        // try not to add redundant line breaks.
        if (i > 0 && s[i - 1] == '\n' && curr == '\n') {
          continue;
        }
        s[i++] = curr;
      }
    } else if (comment == SINGLLC && curr == '\n') {
      comment = NONE;
      // try not to add redundant line breaks.
      if (s[i - 1] != '\n')
        s[i++] = '\n';
    } else if (comment == MULTILC && curr == '/' && prev == '*') {
      comment = NONE;
    }

    prev = curr;
  }

  s[i] = 0;

  printf("Code without comments: \n");
  printf("%s\n", s);

  return 0;
}