/********************************************************/
// R. A. Hillyard
// wordCount1.cpp
// Oct 2000
//
// Program reads a file character by character
// and keeps track of the number of words in the file.
// A word is any string of characters that is proceded and
// followed by one of the following at each end:
// a white space (space, tab, new line), a comma (",") or a period (".")
/********************************************************/
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cctype>
using namespace std;
bool openFiles(ifstream& inData, ofstream& outData);
//pre conditions: inData and outData have been declared as file streams
//post condition: inData and outData will have been opened and function returns true
// if a file fails to open - return false
int main()
{
char next;
int wordCount = 0;
ifstream inData; //declare file streams
ofstream outData;
//open files for reading - check for failure
if( !openFiles(inData, outData))
{
exit(1);
}
//Read data from file
inData.get(next);
while(!inData.eof())
{
//skip any stopping cases
if(isspace(next) || next == ',' || next == '.')
{
inData.get(next);
}
//get next word - read characters until a stopping case or EOF.
else
{
do{
outData.put(next); //echo character to a file
inData.get(next); //get next char
}while( !(isspace(next) || next == ',' || next == '.') && !inData.eof());
wordCount++; //update count
outData.put('\n'); //print new line to file
}
}//end while
outData << "there were " << wordCount << " words in the file\n";
}//end main
/*************************************************************/
/*************************************************************/
bool openFiles(ifstream& inData, ofstream& outData)
{
inData.open("hello.txt");
if(inData.fail())
{
cout << "Failed to open input file\n";
return false;
}
outData.open("helloCount1.txt");
if(outData.fail())
{
cout << "Failed to open output file\n";
return false;
}
return true;
}//end openFiles
/*************************************************************/
/*************************************************************/