-3

Write a function definition that counts the number of words in a line from your text source.

I tried two different codes and got two different results

 countwords()
 {
    ifstream file("notes.txt");
    int count=0;
    char B[80];
    file>>B;
  While (!file.eof())
  {
   cout<<B<<endl;
   file>>B;  
   count++;
   }
}

This gives the desired answer.

The other way around :

 countwords()
 {
    ifstream file("notes.txt");
    char B[80];
    int count=0;
  While (!file.eof())
  {
   file>>B;
   cout<<B<<endl;
   count++;  
   }
}

But this gives an answer which is 1 more than the actual number of words.

Can someone please explain the working of the eof() function and the difference in these two loops?

miyagi_do
  • 107
  • 4

3 Answers3

5

The second version of your answer will always loop one extra time.

Think about this: what happens if file >> B fails? You'll still increment count.

Also, do not loop on eof() because you'll typically loop one too many times. (Why is iostream::eof inside a loop condition considered wrong?)

Instead, do the following:

while(file >> B)
{
   std::cout << B << std::endl;
   ++count;
}

Because your filestream has an implicit conversion to bool that checks the state of it, and returns false if it's not good.

Community
  • 1
  • 1
AndyG
  • 39,700
  • 8
  • 109
  • 143
  • Well i have just started files in c++. so please dont mind if i say something wrong. But how can 'fil>>B' fail? As soon as it reaches the end, the 'eof()' would be true and the loop will terminate? – miyagi_do Jul 28 '15 at 14:16
  • @yasir: Waiting for `eof()` requires that you actually hit the end of file, but what if any of the other error conditions rear their head? File not existing, failed read, or any other `ios_base::failure`? `eof()` will continue returning `false` – AndyG Jul 28 '15 at 15:30
0

The problem is not EOF however to see its working Read this.

Talking about your code, note the file>>B; in first code. Since file>>B; fails in last execution of second code, you get one less the correct answer.

anshabhi
  • 423
  • 6
  • 29
0

The reason for outputting 1 more than the actual number of words: In the 2nd version you output B before reading it for the first time. This is a usage of an uninitialized variable and can result in outputting what will look like garbage, or an empty line. Unreliable code.

Also I would suggest using an std::string instead of char[80] as the type for your variable B.

V-R
  • 1,309
  • 16
  • 32