title: Count the number of times each word occurs in a file
body: <p>Hi I am writing a program that counts the number of times each word occurs in a file. Then it prints a list of words with counts between 800 and 1000, sorted in the order of count. I am stuck on keeping a counter to see if the first word matches the next until a new word appears. In the main I am trying to open the file, read each word by word and call sort in the while loop to sort the vector. Then, in the for loop go through all the words and if the first word equals the second count++. I don't think that is how you keep a counter. </p>
  
  <p>Here is the code:</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;vector&gt;
  #include &lt;algorithm&gt;
  #include &lt;set&gt;
  
  using namespace std;
  
  vector&lt;string&gt; lines;
  vector&lt;int&gt; second;
  set&lt;string&gt; words;
  multiset&lt;string&gt; multiwords;
  
  void readLines(const char *filename)
  {
      string line;
      ifstream infile;
      infile.open(filename);
      if (!infile)
      {       
          cerr &lt;&lt; filename &lt;&lt; " cannot open" &lt;&lt; endl; 
            return; 
      }       
      getline(infile, line);
      while (!infile.eof())
      {
          lines.push_back(line);
          getline(infile, line);
      }  
      infile.close();
  }
  
  int binary_search(vector&lt;string&gt; &amp;v, int size, int value)
  {
      int from = 0;
      int to = size - 1;
      while (from &lt;= to)
      {  
          int mid = (from + to) / 2;
          int mid_count = multiwords.count(v[mid]);
          if (value == mid_count) 
              return mid;
          if (value &lt; mid_count) to = mid - 1;
          else from = mid + 1;
      }
     return from;
  }
  
  int main() 
  {
      vector&lt;string&gt; words;
      string x;
      ifstream inFile;
      int count = 0;
  
      inFile.open("bible.txt");
      if (!inFile) 
      {
          cout &lt;&lt; "Unable to open file";
          exit(1);
      }
      while (inFile &gt;&gt; x){
          sort(words.begin(), words.end());
      }
  
      for(int i = 0;i &lt; second.size();i++)
      {
          if(x == x+1)
          {
              count++;
          }
          else
              return;
      }
      inFile.close();
  }
  </code></pre>