Most frequent character by using arrays

closed account (zwMyAqkS)
Hello,

This is my first semester of programming so don't bash me too hard when it comes to formatting and such. I have been doing well this term but this assignment is on another level for myself.

So far, my code allows the user to open a text file and display its contents. The next step is proving to be quite the challenge. I must find the character that is most frequent in the file I am opening. At the moment, I have no errors but the cout for displaying the most frequent character is empty.
So it reads like this: "The most frequent letter is: "


int main() {

string reply;
string inputFileName;
string line;

ifstream inputFile;

cout << "Input file name: ";
getline(cin, inputFileName);

inputFile.open(inputFileName.c_str());


if ( ! inputFile.is_open()) {
cout << "Unable to open file." << endl;
cout << "Press enter to continue...";
getline(cin, reply);
}

if (inputFile.is_open()){
while (getline(inputFile, line))
{
cout << line << endl;
}
inputFile.close();
}

if (inputFile.is_open()){
while (inputFile.peek() != EOF) {
inputFile.get(character);
}}

int counter[25]; \\ Does not display anything
for (int i = 0; i < character; i++)
counter[i]++;
cout << "The most frequent letter is: " << character << endl;

}
Last edited on
for ascii you can exploit the small size of the table (256 possible characters) to solve this really easily.

unsigned int counts[256] = 0;
for(x = 0; x < length; x++)
counts[(unsigned char)(yourstring[x])] ++;

and then
for(x = 0; x < 256; x++)
if(counts[x])
cout << "letter " << (char)x << " had " << counts[x] << " count\n";

This is a variation of the bucket sort algorithm that is often very handy for certain simple but commonly found chunks of data.

your counting loop is pretty messed up, no offense. you iterate over the value of the character, which is just a number from 0-255, incrementing count each time, and worse, it will be out of bounds because you only have 25 locations (the letter 'a' for example is 65 I think, so that would crash right off). I think you had the right idea and were getting close to what I said, but not quite seeing how to express it. You may want to look at an ascii value chart ... it isn't maybe what you thought (it is not just a-z 0-9 as the first 36 letters for sure, and you will also see that 'a' is not the same as 'A').


Last edited on
Topic archived. No new replies allowed.