Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Exercise 1-23. Write a program to remove all comments from a C program. Don't forget to handle quoted strings and character constants properly. C comments don't nest.*/
- #include <stdio.h>
- #define UnComment 0
- #define StarAfterSlash 1
- #define StarAfterStar 2
- #define SlashAfterStar 3
- #define DoubleSlash 4
- #define MAX 1000
- void removeComment(char *str, int len);
- int main()
- {
- int len;
- char str[MAX];
- removeComment(str, MAX);
- printf("%s", str);
- return 0;
- }
- void removeComment(char *str, int len) {
- int c, i, state;
- i = state = UnComment;
- while ((c = getchar()) != EOF && i < len - 1) {
- switch (c) {
- case '/': if (state == UnComment)
- state = StarAfterSlash;
- else if (state == StarAfterSlash)
- state = DoubleSlash;
- else if (state == SlashAfterStar)
- state = UnComment;
- else if (state == DoubleSlash)
- str[i++] = ' ';
- else
- str[i++] = c;
- break;
- case '*': if (state == StarAfterSlash)
- state = StarAfterStar;
- else if (state == StarAfterStar)
- state = SlashAfterStar;
- else if (state == DoubleSlash)
- str[i++] = ' ';
- else
- str[i++] = c;
- break;
- case '\n': if (state == 1) {
- state = UnComment;
- str[i++] = '/';
- str[i++] = c;
- } else if (state == DoubleSlash) {
- state = UnComment;
- str[i++] = c;
- } else
- str[i++] = c;
- break;
- default: if (state == StarAfterSlash) {
- state = UnComment;
- str[i++] = '/';
- str[i++] = c;
- }
- else if (state == StarAfterStar || state == SlashAfterStar || state == DoubleSlash)
- str[i++] = ' ';
- else
- str[i++] = c;
- }
- }
- str[i] = '\0';
- }
Advertisement
Add Comment
Please, Sign In to add comment