#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/* frequency(const char *filename): the function reads a text file
* and writes the frequency table for each char in a new file.
* Param: filename -- the name of the target file
* Post-condition: the new file contains the frequency table
*/
void getFreq( const char *filename ) {
ofstream freqFile;
//open a file called "char_freqs.txt"
freqFile.open ("char_freqs.txt");
string line;
//read the target file
ifstream targetFile ( filename );
//check whether the target file exists
//print out "The file doesn't exist" if there's no such file
if (targetFile.is_open()) {
int i, size, value, array[256];
char ch;
//initialize the array to be 0
for ( i=0; i <= 255; i++ ) {
array[i] = 0;
}
//check each line in the file
while (! targetFile.eof() ) {
getline ( targetFile,line );
cout << line << endl; //for testing only
size = line.size();
//check each character in the file, and count the frequency
//in the array
for ( i=0; i<size; i++ ) {
value = (int)line[i];
array[value]++;
}
//check the number of new lines
//array[10]++;
}
//print out each character and its frequency
for ( i=0; i <= 255;i++ ) {
ch= (char)i;
if ( array[i] != 0 ) {
freqFile << ch << ' ' << array[i] << endl;
}
}
//close the files
targetFile.close();
freqFile.close();
}
else cout << "The file doesn't exist" << endl;
}
最近熬夜写的C++的部分程序
其实我是来看妹子的。。。 |