Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting the number of lines in a text file

Tags:

c++

file

text

gcc

I'm reading lines off of text file and I'm wondering if this is a good way to go? I had to write the function numberoflines to decrease the number_of_lines variable by one because within the while loop, for every line it read it adds 2 to the number_of_lines variable.

#include <iostream> #include <fstream> using namespace std;  int number_of_lines = 0;  void numberoflines(); int main(){     string line;     ifstream myfile("textexample.txt");      if(myfile.is_open()){         while(!myfile.eof()){             getline(myfile,line);             cout<< line << endl;             number_of_lines++;         }         myfile.close();     }     numberoflines();  }  void numberoflines(){     number_of_lines--;     cout<<"number of lines in text file: " << number_of_lines << endl; } 

Is there any other easier better way?

like image 439
silent Avatar asked Aug 14 '10 04:08

silent


People also ask

How do you count the number of lines in a text file in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

How do you count the number of lines in a text file in c++?

How To Count Lines In A File In C++? To count the lines in a file in c++, we will open the file in the read mode only as there are no output operations needed. Once the file is open we will read the file line by line using the getline() function and count the number of lines.

How do I count the number of lines in a text file using PowerShell?

To count the total number of lines in the file in PowerShell, you first need to retrieve the content of the item using Get-Content cmdlet and need to use method Length() to retrieve the total number of lines.


2 Answers

Your hack of decrementing the count at the end is exactly that -- a hack.

Far better to write your loop correctly in the first place, so it doesn't count the last line twice.

int main() {      int number_of_lines = 0;     std::string line;     std::ifstream myfile("textexample.txt");      while (std::getline(myfile, line))         ++number_of_lines;     std::cout << "Number of lines in text file: " << number_of_lines;     return 0; } 

Personally, I think in this case, C-style code is perfectly acceptable:

int main() {     unsigned int number_of_lines = 0;     FILE *infile = fopen("textexample.txt", "r");     int ch;      while (EOF != (ch=getc(infile)))         if ('\n' == ch)             ++number_of_lines;     printf("%u\n", number_of_lines);     return 0; } 

Edit: Of course, C++ will also let you do something a bit similar:

int main() {     std::ifstream myfile("textexample.txt");      // new lines will be skipped unless we stop it from happening:         myfile.unsetf(std::ios_base::skipws);      // count the newlines with an algorithm specialized for counting:     unsigned line_count = std::count(         std::istream_iterator<char>(myfile),         std::istream_iterator<char>(),          '\n');      std::cout << "Lines: " << line_count << "\n";     return 0; } 
like image 114
Jerry Coffin Avatar answered Sep 28 '22 13:09

Jerry Coffin


I think your question is, "why am I getting one more line than there is in the file?"

Imagine a file:

line 1 line 2 line 3 

The file may be represented in ASCII like this:

line 1\nline 2\nline 3\n 

(Where \n is byte 0x10.)

Now let's see what happens before and after each getline call:

Before 1: line 1\nline 2\nline 3\n   Stream: ^ After 1:  line 1\nline 2\nline 3\n   Stream:         ^  Before 2: line 1\nline 2\nline 3\n   Stream:         ^ After 2:  line 1\nline 2\nline 3\n   Stream:                 ^  Before 2: line 1\nline 2\nline 3\n   Stream:                 ^ After 2:  line 1\nline 2\nline 3\n   Stream:                         ^ 

Now, you'd think the stream would mark eof to indicate the end of the file, right? Nope! This is because getline sets eof if the end-of-file marker is reached "during it's operation". Because getline terminates when it reaches \n, the end-of-file marker isn't read, and eof isn't flagged. Thus, myfile.eof() returns false, and the loop goes through another iteration:

Before 3: line 1\nline 2\nline 3\n   Stream:                         ^ After 3:  line 1\nline 2\nline 3\n   Stream:                         ^ EOF 

How do you fix this? Instead of checking for eof(), see if .peek() returns EOF:

while(myfile.peek() != EOF){     getline ... 

You can also check the return value of getline (implicitly casting to bool):

while(getline(myfile,line)){     cout<< ... 
like image 21
strager Avatar answered Sep 28 '22 13:09

strager