most frequent and least frequent character from a input file

I need to write a program that reads a input file and displays the most frequent character and least frequent one. I have looked at examples from other people and have written one that displays the count of all characters but do not understand how to just show the most and least common one.


#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <string>

using namespace std;
using std::count;
using std::cin;
using std::endl;
using std::vector;

int main()
{
int freq[128]; // frequencies of letters
ifstream inFile; // input file
char ch;

inFile.open("letter_count.txt");
if (!inFile)
{
cout << "The input file could not be opened." << endl;
return 1;
}

// starts counts to zero for each letter
for (int A = 0; A < 128; A++)
{
freq[A] = 0;
}

// Reads file, keeping track of occurance of each letter
ch = inFile.get();
while (ch != EOF)
{
cout << ch;
ch = toupper(ch);
freq[ch]++;
ch = inFile.get();
}
// the output
cout << endl << "Letter frequencies in this file are as follows." << endl;
for (char ch = 'A'; ch <= 'Z'; ch++)
{
cout << ch << " : " << freq[ch] << endl;
}
return 0;
}

1
2
3
4
5
6
7
8
9
10
int mostest, leastest;
mostest= leastest = freq[0];

for(int dx = 0; dx < 128; dx++)
{
     if(freq[dx] > mostest)
      mostest = freq[dx];
     if(freq[dx] < leastest)
       leastest = freq[dx]; 
}


you can get fancy and find the least one that is > 0 if you prefer, as most likely you will have many letter that are unused and it will just spew out one of those (not random, its the last one it found with this logic) and say zero which is about useless, more interesting is that you had 1 x than zero '!' or something. Ill leave tweaking it to you... this is just the basic find biggest algorithm.

Last edited on
thank you, Im still having the issue of displaying just the most frequent character. for some reason my output is a list of all characters with no distinction on which is most and which is least.
This is the code that's producing your output:
1
2
3
4
5
cout << endl << "Letter frequencies in this file are as follows." << endl;
for (char ch = 'A'; ch <= 'Z'; ch++)
{
cout << ch << " : "javascript:thread242523.reply() << freq[ch] << endl;
}

You need to modify this part determine the most and least frequent characters, and then print out just those two.
Topic archived. No new replies allowed.