-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise_1-23.c
executable file
·70 lines (59 loc) · 1.52 KB
/
exercise_1-23.c
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
/* Problem: Write a program to remove all comments from a C program.
* Don't forget to handle quoted strings and character constants
* properly. C comments do not nest.
*/
main() {
int c, d; /* character to read in */
int inComment = 0; /* are we in a comment? */
int inString = 0; /* are we in a string? */
while ((c = getchar()) != EOF) {
/* if we're not in a string, check for the start of one */
if (!inComment && !inString && (c == '"')) {
inString = 1;
}
/* if we're in a string check for the end */
if (!inComment && inString && (c == '"')) {
inString = 0;
}
/* if we're in a string, don't get fooled the next time around by quotes */
if (!inComment && inString && (c == '\\')) {
/* this could be a quote in a string, what's the next character? */
if ((d = getchar()) == EOF) {
putchar(c);
break;
}
if (d == '"') {
putchar(c);
c = d;
}
}
/* if we're not in a comment already, check for the start of one */
if ( !inString && !inComment && (c == '/')) {
/* this could be a comment, what's the next character? */
if ((d = getchar()) == EOF) {
putchar(c);
break;
}
if (d == '*') {
inComment = 1;
}
}
/* print out non-comments */
if (!inComment) {
putchar(c);
}
/* if we're in a comment, check for the end */
if ( inComment && (c == '*')) {
/* this could be a comment, what's the next character? */
if ((d = getchar()) == EOF) {
putchar(c);
break;
}
if (d == '/') {
inComment = 0;
}
}
}
return 0;
}