#include #include // for ifstream #include // for exit() #include // for tolower() #include // for CHAR_MAX #include "apstring.h" #include "prompt.h" #include "apvector.h" // count # occurrences of all characters in a file // written: 8/5/94 // by: Owen Astrachan void Print(const apvector & counts, int total); void Count(istream & input, apvector & counts, int & total); int main() { int totalAlph = 0; apstring filename = PromptString("enter name of input file: "); ifstream input(filename.c_str()); if (input.fail() ) { cout << "could not open file " << filename << endl; exit(1); } apvector charCounts(CHAR_MAX,0); // all initialized to 0 Count(input,charCounts,totalAlph); Print(charCounts,totalAlph); return 0; } void Count(istream & input, apvector & 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 { apstring word; char ch; int k,len; while (input >> word) // read a word succeeded { len = word.length(); // # chars in word for(k=0; k < len; k++) { ch = tolower(word[k]); // convert to lower case if (isalpha(ch)) // is alphabetic (a-z)? { total++; } counts[ch]++; // count all characters } } } void Print(const apvector & counts, int total) // postcondition: all values of counts from 'a' to 'z' printed { cout.setf(ios::fixed); // print 1 decimal place cout.precision(1); char k; for(k = 'a'; k <= 'z'; k++) { cout << k; cout.width(7); cout << counts[int(k)] << " "; cout.width(4); //cout << 100 * double(counts[int(k)])/total << "%" << endl; cout << 100 * static_cast(counts[k])/total << "%" << endl; } }