首页 > 解决方案 > 计算 C 文件中注释字符和单词的程序

问题描述

对于单行注释和阻塞注释,我必须计算 C 文件注释中的字符和单词。这是我所拥有的:

#include <stdio.h>

#define IN = 1
#define OUT = 0

main() {
    int c, nc;
    nc = 0;
    while ((c = getchar()) != EOF) {
        if (c == '/') {
            if (getchar() == '/')
                while (getchar() != '\n')
                    ++nc;
        }  
    }
    
    if (c == '/') {
        if (getchar() == '*')
            while (getchar() != '/')
                ++nc;
    }  
    
    printf("Character Counts: %d\n", nc);
}

它适用于每一行注释 ( //),但它会跳过被阻止的注释 ( /*...*/)。我觉得它永远不会进入被阻止评论的 if 块。非常感谢!

标签: ccountcharacter

解决方案


您的代码中有多个问题:

  • 您必须指定intmain函数的返回类型。问题中的语法已过时。

  • IN和的定义OUT不正确。您应该使用

      #define IN   1
      #define OUT  0
    

    或者

      enum { IN = 1, OUT = 0 };
    
  • 第一个循环消耗标准输入中的所有字节,你在文件的末尾,所以/*...*/注释测试永远不会产生任何东西。

  • 如果在文件结尾之前未找到测试的字节,则循环while (getchar() != '\n')可以永远运行。

  • 您不能单独测试///*...*/评论,因为一个可以隐藏另一个:

      //* this is a line comment that does not start a C style one
    
      /* this comment contains a // but stops here */ return 0;
    
  • 另请注意,您应该解析 C 字符串和字符常量,因为它们可能包含不开始注释的//和/或序列。/*

  • 对于完整的解决方案,您还应该处理转义的换行符。以下是一些病态的例子:

      // this is a line comment that extends \
         on multiple \
         lines (and tricks the colorizer)
    
      /\
      * this is a C comment, but the colorizer missed it *\
      /
    

这个问题在一般情况下解决起来并不简单,但您可以从简单的情况开始。

这是修改后的版本:

#include <stdio.h>

int main() {
    int c, cc, nc = 0;

    while ((c = getchar()) != EOF) {
        if (c == '/') {
            if ((cc = getchar()) == '/') {
                while ((c = getchar()) != '\n')
                    nc++;
            } else
            if (cc == '*') {
                while ((cc = getchar()) != EOF) {
                    if (cc == '*') {
                        if ((cc = getchar()) == '/')
                            break;
                        ungetc(cc, stdin);
                    }
                    nc++;
                }
            }
        }
    }
    printf("Character Counts: %d\n", nc);
    return 0;
}

推荐阅读