SOURCE FILE: 05_wordCounter.cpp



/*
    This program counts the contiguous strings ('words') contained in a file
    called myTextFile.  It prints a numbered list of the 'words' to the
    screen, one word per line, and also writes the list to a file called
    words+counts.
*/

#include <iostream>
#include <fstream>

using namespace std ;

int main (void)
{
   ifstream wordFile ;
   wordFile.open("myTextFile") ;
   if (wordFile.fail())
   {
     cout << "FAILED TO OPEN FILE: " << "myTextFile" << endl ;
     exit(1) ;
   }

   ofstream resultsFile ;
   resultsFile.open("words+counts");
   if (resultsFile.fail())
   {
     cout << "FAILED TO OPEN FILE: " << "words+counts" << endl ;
     exit(1) ;
   }

   int wordCount = 0 ;
   char nextWord[256] ;
        
   while (wordFile >> nextWord)
   {
      wordCount++ ;
      cout << wordCount << " " << nextWord << endl ;
      resultsFile << wordCount << " " << nextWord << endl ;
   }
   
   cout << "\nThere was a total of " << wordCount << " words.\n\n" ;
   resultsFile << "\nThere was a total of " << wordCount << " words.\n\n" ;
        
   wordFile.close() ;
   resultsFile.close() ;

   return 0;
}