0

I have no idea how this would be done, but how would I check the amount of line that exist in a text file.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
  system("pause");
  return 0;
}

So this reads the text file. But lets say there are 2 lines;

HELLO
GOODBYE

This means there are 2 lines, so how would i be able to check how many lines exist?

3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by L7Sqr
0

One way to count lines in a file is to count what you consider to be line delimiters. For instance, if your lines are terminated with \n then you can iterate through the file character-by-character and count the number of times you see that character. That (plus one) will be the total number of lines.

2

You have almost all the code you need to solve the problem. Just add a counter, initialize it to 0, then every time getline() is called increment the counter. That's all there is to it.

0

Yes, AncientDragon is right. I mistakenly looked at cin.getline which may not, in fact, return the entire line.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.