📄 pex14_10.cpp
字号:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <ctype.h>
#pragma hdrstop
#include "binfile.h"
#include "merge.h"
// used for the frequency analysis
struct CharRec
{
char key;
int count;
};
// overload "<" by comparing count fields. used to
// sort a file of CharRec records
int operator< (const CharRec& x, const CharRec& y)
{
return x.count < y.count;
}
// overload "<=" by comparing count fields. used to
// sort a file of CharRec records
int operator<= (const CharRec& x, const CharRec& y)
{
return x.count <= y.count;
}
void main(void)
{
// lcount is a file of CharRec records
BinFile<CharRec> lcount("letcount",INOUT);
CharRec r;
// fin is the textfile to analyze
ifstream fin;
// text file name
char fname[50], c;
long pos;
// initialize lcount to contain 26 records, each containing
// a letter of the alphabet and a count of 0
for(c = 'A';c <= 'Z';c++)
{
// key is c = 'A' .. 'Z', count is 0
r.key = c;
r.count = 0;
// add each record at the end of the file
lcount.Append(r);
}
// open the text file
cout << "Enter the name of the file: ";
cin >> fname;
fin.open(fname,ios::in | ios::nocreate);
if (!fin)
{
cerr << "Unable to open " << fname << endl;
exit(1);
}
// read each character of the file
while (fin.get(c))
// for each alphabetic character,
// translate each lowercase character
// to upper case and update the count field
// of the corresponding record of lcount
if (isalpha(c))
{
// translate lowercase char to upper case
if (islower(c))
c = toupper(c);
// filerecord to which the char belongs
pos = c - 'A';
// read the record from the file
r = lcount.Read(pos);
// update the count field of the file record
r.count++;
// write the modified record to the file
lcount.Write(r,pos);
}
// sort lcount using the natural merge sort
MergeSort(lcount,4);
// go back to record 0 and read through the
// file sequentially
lcount.Reset();
for(int i=0;i < 26;i++)
{
// read current file record and
// display it
lcount.Read(&r,1);
if (r.count != 0)
cout << r.key << ": " << r.count << endl;
}
// close the file and remove it from file system
lcount.Delete();
}
/*
<File "pex14_10.dat">
Missing Mississippi
mornings.
<Run>
Enter the name of the file: pex14_10.dat
O: 1
R: 1
G: 2
P: 2
M: 3
N: 3
I: 7
S: 7
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -