我正在计算" //"的数量。在文件中注释行,而不是注释的总数。 我尝试使用strstr()函数检查字符串" //"在字符串行中,但它是在计算每一行?
case(3) :
while (fgets(line, 300, q)){
if (strstr(line, "//") == NULL) CommentedRows++;
}
我也试过用strchr()来寻找第一次出现的' /'然后检查下一个符号是否为' /',但结果始终为0?
答案 0 :(得分:3)
仅仅因为一行上有//并不意味着有一条评论,因为//可能是字符串的一部分,是另一条评论的一部分,甚至是xmldoc评论的一部分。
假设您想要计算完全注释的行,即,它们以注释开头,可能在它之前有可选的空白字符,那么这可能是一个解决方案:
bool IsFullyCommentedLine(char* line)
{
// For each character in the line
for (int i = 0; line[i] != 0; i++)
{
char c = line[i];
// If it is a / followed by another /, we consider
// the line to be fully commented
if (c == '/' && line[i + 1] == '/')
{
return true;
}
// If we find anything other than whitespace,
// we consider the line to not be fully commented
else if (c != ' ' && c != '\t')
{
break;
}
// As long as we get here we have whitespaces at the
// beginning of the line, so we keep looking...
}
return false;
}
int CountFullyCommentedLines(FILE* file)
{
char buffer[1024];
int commentCount = 0;
while (char* line = fgets(buffer, 1024, file))
{
if (IsFullyCommentedLine(line))
commentCount++;
}
return commentCount;
}
int main(int argc, char* argv[])
{
if (argc == 2)
{
FILE* file = fopen(argv[1], "r");
printf("Number of fully commented lines, ie the ones that start with optional whitespace/tabs and //:\r\n");
printf("%i\r\n", CountFullyCommentedLines(file));
fclose(file);
}
return 0;
}
同样,这假设您不想计算从行中间开始的评论,只评估评论整行的评论。
答案 1 :(得分:2)
这些函数返回指向子字符串开头的指针,如果找不到子字符串,则返回NULL。
所以你应该做
if (strstr(line, "//") != NULL)
{
CommentedRows++;
}
甚至更短
if (strstr(line, "//"))
{
CommentedRows++;
}
然而,这只是告诉你line
在某处包含了C-“string”"//"
,而这被解释为C ++ / C99注释是另一个故事。