c - 计算 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 块。非常感谢!
解决方案
您的代码中有多个问题:
您必须指定
int
为main
函数的返回类型。问题中的语法已过时。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;
}
推荐阅读
- amazon-web-services - 捕获 lambda 函数的开始和结束
- swift - 来自 Firebase 存储的图像不会在我的 UIImageView 中刷新(swift)
- python - 我从 sklearn 得到负值作为 IterativeImputer 的输出
- r - 使用我自己的排序功能对多个数据框列进行排序
- python - 在 print() 中搜索由 .format 决定的某个单词
- python-3.x - 用于测试与多个服务器的 RDP 连接的脚本
- c - STM8L051F3 GPIO 初始配置
- c++ - 按属性搜索和提取 XML 节点
- c++ - `sgemm` 的维度参数如何工作?
- java - 如何从 Kafka 主题获取记录总数并保存到 HDFS?