samir82show

c_ch01_ex23.c

Nov 1st, 2014
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.15 KB | None | 0 0
  1. /*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.*/
  2. #include <stdio.h>
  3. #define UnComment 0
  4. #define StarAfterSlash 1
  5. #define StarAfterStar 2
  6. #define SlashAfterStar 3
  7. #define DoubleSlash 4
  8. #define MAX 1000
  9. void removeComment(char *str, int len);
  10. int main()
  11. {
  12. int len;
  13. char str[MAX];
  14. removeComment(str, MAX);
  15. printf("%s", str);
  16. return 0;
  17. }
  18. void removeComment(char *str, int len) {
  19. int c, i, state;
  20. i = state = UnComment;
  21. while ((c = getchar()) != EOF && i < len - 1) {
  22. switch (c) {
  23. case '/': if (state == UnComment)
  24. state = StarAfterSlash;
  25. else if (state == StarAfterSlash)
  26. state = DoubleSlash;
  27. else if (state == SlashAfterStar)
  28. state = UnComment;
  29. else if (state == DoubleSlash)
  30. str[i++] = ' ';
  31. else
  32. str[i++] = c;
  33. break;
  34. case '*': if (state == StarAfterSlash)
  35. state = StarAfterStar;
  36. else if (state == StarAfterStar)
  37. state = SlashAfterStar;
  38. else if (state == DoubleSlash)
  39. str[i++] = ' ';
  40. else
  41. str[i++] = c;
  42. break;
  43. case '\n': if (state == 1) {
  44. state = UnComment;
  45. str[i++] = '/';
  46. str[i++] = c;
  47. } else if (state == DoubleSlash) {
  48. state = UnComment;
  49. str[i++] = c;
  50. } else
  51. str[i++] = c;
  52. break;
  53. default: if (state == StarAfterSlash) {
  54. state = UnComment;
  55. str[i++] = '/';
  56. str[i++] = c;
  57. }
  58. else if (state == StarAfterStar || state == SlashAfterStar || state == DoubleSlash)
  59. str[i++] = ' ';
  60. else
  61. str[i++] = c;
  62. }
  63. }
  64. str[i] = '\0';
  65. }
Advertisement
Add Comment
Please, Sign In to add comment