-1

I have the following task.

I need to check how many characters, words and rows, are in the file, that I'm opening. So I came to this problem.

When I need to position the get pointer, again in the beginning, it doesn't work. The while((getline(f, charCount)), just get passed away, it doesn't enter.

Here's the code:

void count(ifstream &f)
{
    int countChar = 0, countWord = 0, countRow = 0;
    string charCount;
    string wordCount;
    while (!f.eof())
    {
        f >> wordCount;
        countWord++;

    }
    cout << " Words : " << countWord << endl;
    f.seekg(ios::beg);
    while (getline(f, charCount))
    {
        countChar += charCount.length();
        countRow++;
    }

    cout << "Characters: " << countChar << endl;
    cout << "Rows : " << countRow << endl;
}
b4hand
  • 8,601
  • 3
  • 42
  • 48

1 Answers1

3

Use of

while (!f.eof())
{
    f >> wordCount;
    countWord++;
}

is wrong.

It should be

while (f >> wordCount)
{
    countWord++;
}

Further reading: Why is iostream::eof inside a loop condition considered wrong?.

Once EOF has reached, you'll need to clear the error flags of the stream before you can use it again.

f.clear();
f.seekg(ios::beg);
while (getline(f, charCount)) ...
Community
  • 1
  • 1
R Sahu
  • 196,807
  • 13
  • 136
  • 247