/* letters.cpp from Astrachan, pp 348-350 */ #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; } } /* Sample output prompt> letters enter name of input file: letters.cpp a 88 7.2% n 98 8.0% b 5 0.4% o 105 8.6% c 99 8.1% p 46 3.8% d 36 3.0% q 0 0.0% e 89 7.3% r 73 6.0% f 28 2.3% s 59 4.8% g 6 0.5% t 156 12.8% h 35 2.9% u 56 4.6% i 97 8.0% v 12 1.0% j 0 0.0% w 10 0.8% k 14 1.1% x 6 0.5% l 67 5.5% y 1 0.1% m 30 2.5% z 4 0.3% prompt> letters enter name of input file: bylaws.tex [an English document] a 2763 8.2% n 2346 7.0% b 384 1.1% o 2408 7.2% c 1530 4.6% p 1020 3.0% d 1222 3.6% q 42 0.1% e 4455 13.3% r 2401 7.2% f 972 2.9% s 2113 6.3% g 562 1.7% t 3439 10.3% h 1228 3.7% u 967 2.9% i 2432 7.3% v 257 0.8% j 23 0.1% w 256 0.8% k 80 0.2% x 102 0.3% l 1014 3.0% y 455 1.4% m 1036 3.1% z 26 0.1% l */