C - Remove all comments from a C program

超、凢脫俗 2023-01-09 12:39 231阅读 0赞

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

  1. /*
  2. * Write a program to remove all comments from a C program.
  3. * Don't forget to handle quoted strings and character constants properly.
  4. * C comments don't nest.
  5. *
  6. * RemoveComment.c - by FreeMan
  7. */
  8. #include <stdio.h>
  9. #define MAXLINE 1024 /* Max input line size */
  10. char line[MAXLINE]; /* Current input line */
  11. int GetLine(void);
  12. int main()
  13. {
  14. int in_comment, len;
  15. int in_quote;
  16. int t;
  17. in_comment = in_quote = t = 0;
  18. while ((len = GetLine()) > 0)
  19. {
  20. t = 0;
  21. while (t < len)
  22. {
  23. if (line[t] == '"')
  24. {
  25. in_quote = 1;
  26. }
  27. if (!in_quote)
  28. {
  29. if (line[t] == '/' && line[t + 1] == '*')
  30. {
  31. t = t + 2;
  32. in_comment = 1;
  33. }
  34. if (line[t] == '*' && line[t + 1] == '/')
  35. {
  36. t = t + 2;
  37. in_comment = 0;
  38. }
  39. if (in_comment == 1)
  40. {
  41. t++;
  42. }
  43. else
  44. {
  45. printf("%c", line[t]);
  46. t++;
  47. }
  48. }
  49. else
  50. {
  51. printf("%c", line[t]);
  52. t++;
  53. }
  54. }
  55. }
  56. return 0;
  57. }
  58. /* GetLine: Specialized version */
  59. int GetLine(void)
  60. {
  61. int c, i;
  62. extern char line[];
  63. for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
  64. {
  65. line[i] = c;
  66. }
  67. if (c == '\n')
  68. {
  69. line[i] = c;
  70. ++i;
  71. }
  72. line[i] = '\0';
  73. return i;
  74. }

发表评论

表情:
评论列表 (有 0 条评论,231人围观)

还没有评论,来说两句吧...

相关阅读