// Program file: stats.cpp #include #include "boolean.h" #include "cstrlib.h" // Function: analyze_sentence // Computes and display statistics for a sentence entered at the keyboard void analyze_sentence(); // Function: update_statistics // Updates longest word, word count, and character count // // Inputs: current input word, the longest word, a word count, a character count // Outputs: the longest word, a word count, a character count void update_statistics(string word, string &longest_word, int &word_count, int &char_count); // Function: display_statistics // Displays longest word, word count, and character count, and average length of // words in a sentence // // Inputs: the longest word, a word count, a character count void display_statistics(string longest_word, int word_count, int char_count); void main() { char query; do { cout << "Enter a sentence [terminating with a period ('.')]: "; analyze_sentence(); cout << "Run once more? [Y/N]: "; cin >> query; } while ((query == 'Y') || (query == 'y')); } void analyze_sentence() { string word, longest_word; int word_count, char_count; word_count = 0; char_count = 0; do { cin >> word; update_statistics(word, longest_word, word_count, char_count); } while (word.nth_char(word.length()) != '.'); display_statistics(longest_word, word_count, char_count); } void update_statistics(string word, string &longest_word, int &word_count, int &char_count) { int length = word.length(); if (length > longest_word.length()) longest_word = word; ++word_count; char_count = char_count + length; } void display_statistics(string longest_word, int word_count, int char_count) { cout << endl << "Number of words: " << word_count << endl; cout << "Number of characters: " << char_count << endl; cout << "Average length of a word: " << char_count / word_count << endl; cout << "Longest word: " << longest_word << endl << endl; }