0

I've got the following code where I'm trying to count the number of lines in an input file, and I've tried several different ways of implementing it, but no luck.

int checkData(string File)
{
string temp;
int linecount = 0;
ifstream input(File);
input.open(File);

while ()
    {   
        getline(input,temp);
        linecount++;
        temp.clear();
    }
return linecount;

}

So far, I've tried:

while(!input.eof())
    {
     ...
    }

and

while(getline(input,temp).good())
    {
     ...
    }

The first doesnt break the loop, and I'm not quite sure why. (I'm fairly sure) that getline has a built in stream buffer, so it should automatically read the net line everytime I pull in a line and throw it back out, but no dice. For the second, the loop doesn't execute at all, which still doesn't make sense to me (that says that the first line of file isn't good input?). The test file I'm using is:

this is a test     this     Cake
this is a test     this     Cake
this is a test     this     Cake
this is a test     this     Cake

So linecount should be returning as 4 when executing correctly. Before I execute this, I've already checked to make sure the file is opening correctly.

output

1 Answers1

3
int number_of_lines = 0;
string line;
ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
    ++number_of_lines;

Hope it helps.

Eklavya
  • 15,459
  • 4
  • 14
  • 41