Write a program that determines the frequency of each char in an input le. Your program
should
• read in an unknown number of chars from an input le named input.txt,
• using a function written by you, determine the frequency of occurrence of each char in
the list
• write each char followed by the frequency to the output le output.txt.
• The chars should appear in the output le in the same order as they rst appeared in
the input le.
First draw a
ow chart and then attempt the code.
Example 1
Example input and output les can be seen in Listings 9 and 10.
Listing 9: Example of input.txt
1 a
2 a
3 f
4 e
5 v
6 x
7 a
8 v
9 f
10 f
11 f
12 g
Page 4 of 5
Listing 10: Example of output.txt
1 a 3
2 f 4
3 e 1
4 v 2
5 x 1
6 g 1
Example 2
Example of additional input and output les can be seen in Listings 11 and 12.
Listing 11: Example of input.txt
1 a
2 b
3 a
4 b
5 a
6 b
7 b
Listing 12: Example of output.txt
1 a 3
2 b 4
#include <fstream>
#include <cctype>
using namespace std;
int main() {
char appearedCh[26];
int frequency[26];
int numCh = 0;
char ch;
ifstream ifs("input.txt");
while ( (ifs >> ch)) {
ch = tolower(ch);
if ( ch < 'a' || ch > 'z') {
continue;
}
int i;
for (i=0; i<numCh; ++i) {
if (appearedCh[i] == ch) {
break;
}
}
if (i == numCh) {
appearedCh[i] = ch;
frequency[i] = 1;
numCh++;
}
else {
frequency[i]++;
}
}
ifs.close();
ofstream ofs("output.txt");
for (int i=0; i<numCh; ++i) {
ofs << appearedCh[i] << " " << frequency[i] << endl;
}
ofs.close();
}
Comments
Leave a comment