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?

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.

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.