#include #include // for ifstream #include // for tolower(), isalpha() #include using namespace std; #include "prompt.h" #include "tvector.h" // count # occurrences of all characters in a file // written: 8/5/94, Owen Astrachan, modified 5/1/99 // modified by Albert Levi 8/14/2002 and 12/17/2007 void Print(const tvector & counts, int total); tvector Count (istream & input, int & total); int main() { int totalLetters = 0; // counter for all letters string filename = PromptString("enter name of input file: "); ifstream input(filename.c_str()); if (input.fail() ) { cout << "could not open file " << filename << endl; return 0; } tvector charCounts(26,0); // 0 for 'a', 1 for 'b', 2 for 'c', so on, 25 for 'z' // all initialized to 0 charCounts = Count(input, totalLetters); Print(charCounts, totalLetters); return 0; } tvector Count (istream & input, int & total) // precondition: input open for reading and file pos. pointer is at the beginning // counts[k] == 0, where 0 <= k and k < 26 // postcondition: counts[k] = # occurrences of letter: 0th entry for 'a', 1st for 'b', so on // total = # alphabetic characters { char ch; tvector counts(26,0); while (input.get(ch)) // read a character { if (isalpha(ch)) // is alphabetic (a-z) or (A-Z)? { total++; ch = tolower(ch); // convert to lower case counts[ch - 'a']++; // count all characters } } return counts; } void Print(const tvector & counts, int total) // precondition: total = total number of letters // postcondition: all values of counts from 'a' (0) to 'z' (25) printed { cout.setf(ios::fixed); // print real numbers in decimal point notation cout.precision(1); // print 1 decimal place int k; for(k = 0; k <= 25; k++) { cout << char(k + 'a') << "\t" << counts[k] << "\t"; cout << 100 * double(counts[k])/total << "% \n"; } }