#include #include // for ifstream #include // for exit() #include // for tolower() #include // for CHAR_MAX #include #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 void Print(const tvector & counts, int total); void Count(istream & input, tvector & counts, int & total); int main() { int totalAlph = 0; string filename = PromptString("enter name of input file: "); ifstream input(filename.c_str()); if (input.fail() ) { cout << "could not open file " << filename << endl; exit(1); } tvector charCounts(CHAR_MAX+1,0); // all initialized to 0 Count(input,charCounts,totalAlph); Print(charCounts,totalAlph); return 0; } void Count(istream & input, tvector & counts, int & total) // precondition: input open for reading // counts[k] == 0, 0 <= k < CHAR_MAX // postcondition: counts[k] = # occurrences of character k // total = # alphabetic characters { char ch; while (input.get(ch)) // read a character { if (isalpha(ch)) // is alphabetic (a-z)? { total++; } ch = tolower(ch); // convert to lower case counts[ch]++; // count all characters } } void Print(const tvector & counts, int total) // precondition: total = total of all entries in counts['a']..counts['z'] // postcondition: all values of counts from 'a' to 'z' printed { const int MIDALPH = 13; cout.setf(ios::fixed); // print 1 decimal place cout.precision(1); char k; for(k = 'a'; k <= 'm'; k++) { cout << k << setw(7) << counts[k] << " "; cout << setw(4) << 100 * double(counts[k])/total << "% \t\t"; cout << char(k+MIDALPH) << setw(7) << counts[k+MIDALPH] << " "; cout << setw(4) << 100 * double(counts[k+MIDALPH])/total << "%" << endl; } }