-3

I'm new to time complexity in algorithms. This is the code for counting the number of words in a text file. My problem is that every time my program prints one more than the actual count of words in the file, like if I have 11 words in my file it prints 12.

#include<fstream>
#include<iostream>
#include<string>
using namespace std;   
/* main function  */
 void main()
 {
     ifstream inFile; //file file name
     string fileName;
      string word;
      int count = 0;
       inFile.open("example.txt");
         while(!inFile.eof())
           {
           inFile >> word;  
                   ++count;
               }
     cout << "Number of words in file is " << count<<endl; 
inFile.close();

}
//this file is for counting the number of words in a text file**
Rahul Nori
  • 648
  • 6
  • 16
amal
  • 1
  • 1

1 Answers1

1

First thing first : Why is iostream::eof inside a loop condition considered wrong? This will answer your extra count problem.

Then, coming to complexity, since it will go though every N words till it reaches end of file, it will be done in O( N ) time

Also, void main() is not legal c++, main should return int

Community
  • 1
  • 1
P0W
  • 42,046
  • 8
  • 62
  • 107