#include #include // for ifstream #include #include "prompt.h" // finds the total number of words with more than the average word length in a file void AverageWordLength (ifstream & in, int & numWords, double & avg) // pre: file is opened successfully before the function is called and filepos is at the beginning // post: return the average word length of in. If file is empty return 0 as average word length { int sum = 0; string word; numWords = 0; while (in >> word) { numWords++; sum += word.length(); } if (numWords != 0) avg = double(sum)/numWords; else avg = 0; } int main() { string word; int longercount = 0; // counter for words longer than average int allwords; double average; ifstream input; string filename = PromptString("enter name of file: "); input.open(filename.c_str()); // bind input to named file if (input.fail()) //if filename is invalid { cout << "cannot open " << filename << endl; return 0; //stop program } AverageWordLength(input, allwords, average); // calculate the average word length input.clear(); // clear the error flags input.seekg(0); // reset the filepos to the beginning of the file while (input >> word) // until the end of the file { if (word.length() > average) // if the next word is longer than the average { longercount++; // count it } } cout << "number of words read = " << allwords << endl; cout << "average word length = " << average << endl; cout << "number of words longer than average = " << longercount << endl; return 0; }