2015-02-06 29 views
0

我想計算一個文件中「//」註釋行的數量,而不是總數的註釋。 我試過使用strstr()函數來檢查字符串「//」是否在字符串行中,但它正在計算每一行?如何計算C中「//」註釋行的數量?

case(3) : 

    while (fgets(line, 300, q)){ 

    if (strstr(line, "//") == NULL) CommentedRows++; 

    } 

我也試圖與,和strchr()尋找的「/」第一次出現,然後檢查是否下一個符號是「/」,但結果始終爲0?

+1

你是不是指'if(strstr(line,「//」))CommentedRows ++;'? – Gopi 2015-02-06 17:05:09

+2

僅供參考 - 您的代碼也會匹配'printf(「//」);'不確定這對您是否有問題。 – user590028 2015-02-06 17:06:52

+0

'如果(strstr(line,「//」)!= NULL)'這就是我認爲應該是代碼 – cmidi 2015-02-06 17:08:34

回答

2

strstr()'s documentation

這些函數返回一個指向字符串,或NULL的開始。如果沒有找到子。

所以,你應該做的

if (strstr(line, "//") != NULL) 
{ 
    CommentedRows++; 
} 

,甚至更短的

if (strstr(line, "//")) 
{ 
    CommentedRows++; 
} 

然而,這只是告訴你,line包含C- 「串」 "//"地方,閹這被解釋作爲C++/C99的評論是另一回事。

+0

主席先生,我認爲應該檢查這2個必須是第2個字符的 – Gopi 2015-02-06 17:08:26

+1

@Gopi:'//'可以開始評論,即使它們不是第一個字符,例如像這行......「 std :: cout << std :: endl; //輸出空行' – 2015-02-06 17:11:19

+0

if(strstr(line,「//」)) { CommentedRows ++; } results 0 evry time – 2015-02-06 17:15:36

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

一個很好的例子就是OP正在編寫的程序。 – djechlin 2015-02-06 17:10:36

+0

我不在乎「//」是否是評論以外的內容 – 2015-02-06 18:08:23