Feb 16, 2018 at 4:24am UTC
My code docent work! its spouse to return the most frequent appearing letter with the total occurrences. I get some other letters! and also, how can I use reference variables?
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int mostCommon(int[] ,const char[]);
int leastCommon(int[], const char[]);
int main()
{
const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
int text[26] = { 0 };
int maxNumber, leastNumber;
ifstream inputFile;
string filename;
string lineReader;
cout << "Enter the file name" <<endl;
cin >> filename;
inputFile.open(filename);
if(inputFile.is_open())
{
char count;
while (inputFile.get(count))
{
if (isalpha(count))
{
count = toupper(count);
int index = count - 'A';
text[index]++;
}
}
for(int i = 0; i<26; ++i )
{
cout << " " << alphabet[i] << " occurs ";
cout << text[i] << " times\n" ;
}
mostCommon(text,alphabet);
leastCommon(text, alphabet);
inputFile.close();
}
else
{
cout << "Error! file not found "<<endl;
}
}
int mostCommon(int text[], const char alphabet[])
{
char highestLetter;
for(int i = 0; i < 1; i++)
{
if(text[i] > alphabet[i])
highestLetter = alphabet[i];
}
cout << "Highest value is " << highestLetter <<endl;
return 0;
}
int leastCommon(int text[], const char alphabet[])
{
int least =0;
for(int count = 1; count < alphabet[count]; count ++)
{
if(text[count] < least)
least = text[count];
}
return least;
}
Feb 16, 2018 at 7:27am UTC
Can use containers for such things. Even a plain array is ok
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
const std::string text = "banana" ;
std::pair<char ,int > results[26] ;
for (int i = 'a' ; i <= 'z' ; ++i)
results[i - 'a' ].first = i;
for (char c : text)
++results[c - 'a' ].second;
auto it = std::max_element(std::begin(results), std::end(results), [](auto & lhs, auto & rhs) { return lhs.second < rhs.second; });
std::cout << it->first << " appeared " << it->second << " times" << std::endl;
}
Last edited on Feb 16, 2018 at 7:34am UTC