Skip to content

Creating a program that reads counts the number of lines in a C++ file

An answer to this question on Stack Overflow.

Question

im looking to count the number of lines in a code i have figured that i need to look for a specific character from the file and increment by one each time that it is found. Now i have a general gist of it but im having trouble figuring out how to read each line in the file. I have posted what i have so far. Any help would be appreciated

#include<fstream>
#include <iostream>
using namespace std;
 int main()
{
   ifstream readfile;
   readfile.open("project1b.cbp");
   int number_of_lines=0;
   char = ch;
   while(ch !=EOF)
   {
       if(ch!='endl'||';')
        number_of_lines++;
   }
    return 0;
}

Answer

Try this:

#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char **argv){
  if(argc!=2){
    cout<<"Syntax: "<<argv[0]<<" <FILENAME>"<<endl;
    return -1;
  }
  ifstream readfile(argv[1]);
  if(!readfile.good()){
    cout<<"Failed to open file: '"<<argv[1]<<"'!"<<endl;
    return -1;
  }
  int number_of_lines=0;
  while(readfile.good()){
    char ch=readfile.get();
    if(ch=='\n'|| ch==';')
      number_of_lines++;
  }
  cout<<"Number of lines: "<<number_of_lines<<endl;
  return 0;
}

Some differences from your code.

  • I use argc and argv so that the user can specific a file name on the command line.
  • I load the file with ifstream readfile(argv[1]). This fits the RAII (Resource Acquistion is Initialization) scheme commonly used in C++. I don't use a close() statement because the ifstream will go out of scope and automatically clean itself up. Using RAII makes your code cleaner and less-prone to errors.
  • I use get() to acquire new characters from the character stream. This was missing in your code.
  • The end of the line occurs when the \n (newline) character is the one we're currently looking at, or if we are looking at the ; character. endl is not a character constant - it's more of a stream manipulator - so you cannot use it in the manner you do, nor to do comparisons of this sort in general.
  • Note that the or operator (||) divides two complete logic statements, the way in which you use it ((ch!='endl'||';')) does not work the way you think it does.
  • I opt to use K&R style bracing rather than your heathen Allman/GNU style. (This is something of a joke, but I encourage you to try several different styles and find one that's right for you. I prefer K&R for SO because the code is more compact.

You should ask yourself if this is really the way you want to count lines of code. For instance, a for construct (for(int i=0;i<N;++i)) will end up looking like three lines of code using your metric.