Program to read a code and count the number of lines in it,do not include comments and blank lines in count

user379888 picture user379888 · Oct 5, 2010 · Viewed 11.2k times · Source

I am trying to create a program which, given an input file, returns the count of all the lines of code in the input file, excluding blank lines and comment lines. I have written the following code, however I need help with how to exclude lines containing comments and blank lines.

#include<stdio.h>
int main()
{
    int count;
    char ch;
    FILE *fptr;
    clrscr();
    fp=fopen("test.cpp","r");
    if(fp==EOF)
        {
        perror("Error:");
        }
    else
    {
        while(ch!=EOF)
        {
            ch=fgetc(fptr);
            if(ch=='\n')
                count++;
            if(ch=='\\')
                count--;
            if(ch=='\*')
                          {
                while(ch!='*\')
                                    {
                    ch=fgetc(fptr);
                                    }
            }
        }
    printf("the lines in the code are %d\n",count);
    fclose (fptr)
    }
    getchar();
    return 0;
}

How can I modify the above code so that blank lines and comment lines are not counted?

Answer

pmg picture pmg · Oct 8, 2010

If you read the input file character by character, you'll have a lot more work than if you read it line by line. After all you're counting lines ...

psudocode

    1. initialize line count to 0
    2. read a line
    3. end of file? yes: goto 7
    4. is it a good line? yes: goto 5; no: goto 2
    5. increment line count
    6. repeat from 2
    7. output line count

Now you ask ... what is a good line?
For an approximation of the program, I suggest you consider a line everything except lines composed of 0 or more whitespace. This approximation will count comments, but you can develop your program from here.

The following version ignores lines with // coments on an otherwise empty line.

Version 3 could ignore lines containing both /* and */

and version 4 would deal with multi line comments.

Above all, have fun!