僅僅因爲一行有// //並不意味着有註釋,因爲//可能是字符串的一部分,是另一個註釋的一部分,或者甚至是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;
}
同樣,這假定你不想計算從行中開始的評論,只是評論整個行的評論。
你是不是指'if(strstr(line,「//」))CommentedRows ++;'? – Gopi 2015-02-06 17:05:09
僅供參考 - 您的代碼也會匹配'printf(「//」);'不確定這對您是否有問題。 – user590028 2015-02-06 17:06:52
'如果(strstr(line,「//」)!= NULL)'這就是我認爲應該是代碼 – cmidi 2015-02-06 17:08:34