// CSE 143 Au00 HW1 Sample Solution // HP 9/00 // main.cpp - Main program and string processing functions #include #include #include #include using namespace std; #include "wordlist.h" const int MAX_FILENAME_LENGTH = 300; // longest input file name // = copy of s with all punctuation removed // (punctuation as defined by ispunt() in cctype) string strip_punctuation(string s) { string result = ""; for (int k = 0; k < s.length(); k++) if (!ispunct(s[k])) result += s[k]; return result; } // = copy of s with all upper-case characters converted to lower-case string lower_case(string s) { for (int k = 0; k < s.length(); k++) s[k] = tolower(s[k]); return s; } // Read file name, open file, read and count words in the file, then // print the most frequent words in order of decreasing frequency. // Number of words to be printed is also requested from the user. int main() { char fn[MAX_FILENAME_LENGTH]; // input file name string word; // current word from input file WordList word_list; // list of word/frequency pairs int nWords_to_print; // # words to be printed cout << "Please enter file name: "; cin >> fn; // open input file; exit if this fails ifstream infile(fn); if (!infile) { cout << "unable to open input file" << endl; return 1; } // read words and add to word_list make_empty(word_list); while (infile >> word) { word = lower_case(strip_punctuation(word)); if (word.length() > 0) count_word(word, word_list); } // get number of words to print from user cout << "How many word/frequency pairs do you want? "; cin >> nWords_to_print; // print word/frequency pairs in order sort_words(word_list); print_n_words(nWords_to_print, word_list); return 0; }