Remove Comments and blank lines from LOC.

Hi all.. i have a program to count LOC i.e. Line of code of a source file of any C++ program. The LOC shud not contain the comments count and also the blank lines. Now i m able to count to total lines of the program but the comments and the blank line count is proving very tough for me. coz // and /* both type of comments shud not be counted. if // comes after some valid C++ statement then it shud be counted as an LOC. for exa.

int a ; // variable declared.

This shud be counted as an LOC

int b=10 ; /* variable declared
with the value of 10 /*

this shud be counted as one LOC and one comment line.
also how to count the blank lines ??
so pls anyone who can solve this problem then pls help me with this program.
You need to maintain the state of whether you're in a comment block across lines.

If a similar app I wrote some time ago:
int a ; // variable declared. would count as a comment line and a line of code.

1
2
int b=10 ; /* variable declared
with the value of 10 /* */
would be counted as one code line, two comment lines.

Basically, you need to track what the compiler would do, and do that.
ok but how to apply the logic ??? following is the code by far wat i was able to do.. but its not giving the correct answer for counting // comments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
char ch2 , buf[2000];
ifstream openfile2("file.cpp");
int i = 0;
while(!openfile2.eof())
{
openfile2.get(ch2);
buf[i]=ch2;
i++;
}

for(int j = 0 ; j<sizeof(buf); j++)
{
if(buf[j]==10)
{
for(int k=j;k<sizeof(buf);k++)
{
if((buf[k+1]==32) || (buf[k+1]==9))
{
j++;
}
}
}

if((buf[j]==47) && (buf[j+1]==47))
{
cnt3++;
}

}
cout<<"\n\tTotal Comments: " <<cnt3;
//cout<<buf;
openfile2.close();
Last edited on
Any chance of you editing your post and using the code format tag to format your code?

Don't waste time reading characters at a time. Read a while line at once and process that.
ya i did read the line using getline() function but there are so many conditions to check for comments counting, so dropped tht idea. but if u can suggest a better way with tht then pls help.
i ve editted the code in a proper format. thanks
This is the sample code for counting the line and ingnoring the commented line "//" .
Hope you will write the logic for "/*" and "*/"
Hope this helps


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std; 

int _tmain(int argc, _TCHAR* argv[])
{
	ifstream testfile;
	string stringline; 
	size_t found; 
	int positioncount = 0; 
	char arry[100];
	testfile.open("C:\\data.txt");
	while(!testfile.eof())
	{
		testfile.getline(arry , 50);
		stringline = arry;
		if(stringline.find("//") == 0)
		{
			continue;
		}
		positioncount++;
		
	}
	
	testfile.close();
	return 0;
}
Topic archived. No new replies allowed.