程式碼數統計核心演算法

來源:互聯網
上載者:User

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
char  str[1024];//一行文本的最大值為1024
//功能:刪除文本中一行的空白符(空格、定位字元)
//傳回值:若文本行為空白,則返回0;
//   若文本行非空,則返回非零值(字元的個數)
int CheckAndDeleteBlank(char *str)
{
  int len;
  len = strlen(str);
  int j = 0;
  for (int i = 0; i < len; i++)
  {
   if (str[i] != ' ' && str[i] != '\t')//去文本中的掉空白符
   {
     str[j] = str[i];
     j = j + 1;
   }
  }
  str[j] = '\0';
  if (str[0] == '\n')
  {
return 0;
  }
  else
  {
     return j;
  }
}

int checkflag(char *str)
{
int flag = 0;
int len = strlen(str);
int i = 0;

while (str[i] != '\0')
{
if (str[i+1] == '\0')
{
break;
}

if(str[i] == '/' && str[i + 1] == '*')
{
flag++;
}
if (str[i] == '*' && str[i + 1] == '/')
{
flag = 0;
}
i++;
}
if (flag > 0)
{
flag = 1;
}
return flag;
}

int main()
{
int totalLineNumber = 0,commentLineNumber = 0,blankLineNumber = 0;
int result;
int flag = 0;
FILE  *fp;
char filename[] = "f:\\main.cpp";
cout << "Enter a filepath/filename:\n";

fp = fopen(filename, "r+");
if(fp == NULL)

cout << "Can't open file" << endl;
return -1;
}
while (fgets(str,1024,fp))  //逐行讀取
{
result = CheckAndDeleteBlank(str);//去掉一行字串中的空白符
cout << str;//目標檔案去掉空白符後的結果
if (flag == 0)  //start
{
if(result == 0) 
blankLineNumber++;
if (str[0] == '/' && str[1] == '/')
{
commentLineNumber++;
}
if (str[0] == '/' && str[1] == '*')
{

commentLineNumber++;
flag = checkflag(str);
}
if (str[0] != '/')//
{
flag = checkflag(str);
}
}     
else
{
commentLineNumber++;
if (strstr(str,"*/") != NULL  && checkflag(str) == 0)
{
flag = 0;
}

}
totalLineNumber++;
}
fclose(fp);
cout << endl;
cout << "filename:" << filename << endl;
cout << "Code: " << totalLineNumber - commentLineNumber - blankLineNumber << endl;
cout << "Comment: " << commentLineNumber << endl;
cout << "Blank: " << blankLineNumber << endl;
cout << "Total Number of Line : " << totalLineNumber << endl;
getchar();
return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.