Posted by: cp21 September 25, 2015
C++
Login in to Rate this Post:     0       ?        
this code actually compiles and shows right result, however i can't use this because it is using C-strings and C-strings functions

I am only allowed to use C++ string class and no global variables are to be used

#include
#include
#include
#include
#include
#include
#include

using namespace std;


class LetterCounter
{
public:
LetterCounter();

void ReadFile(char *lower_count);
void ParseTextAndCountLetters();
void getMinMaxChar(char *minChar, char *maxChar, int *minCount, int *maxCount);

~LetterCounter();


private:
FILE *fpt;
char line[15];

int frequency[26];
string stext;

};


LetterCounter::~LetterCounter()
{
// empty destructor
//
}

LetterCounter::LetterCounter()
{
for (int i = 0; i < 26; i++)
frequency[i] = 0;
//empty constructor

return;
}




void LetterCounter::ReadFile(char *letter_count)
{
errno_t err;
if ((err = fopen_s(&fpt, letter_count, "r")) == 0)
{
printf("\nopenend file %s", letter_count);

while (!feof(fpt))
{
fscanf_s(fpt, "%s", line, _countof(line));
stext.append(line);
}

fclose(fpt);
}
else
{
printf("\nCould not open %s", letter_count);
}

return;
}

void LetterCounter::ParseTextAndCountLetters()
{
int i;
int length = stext.length();


for (i = 0; i < length; i++)
{
char c = toupper(stext.c_str()[i]);

if (c > 64 && c < 92)
{
printf("%c", c);
frequency[c - 65]++;
}

}

return;
}

void LetterCounter::getMinMaxChar(char *minChar, char *maxChar, int *minCount, int *maxCount)
{

*minChar = *maxChar = 0;
*minCount = *maxCount = 0;

*minChar = frequency[0];

for (int i = 0; i < 26; i++)
{
if (frequency[i] > *maxCount)
{
*maxCount = frequency[i];
*maxChar = i + 65;
}

if (frequency[i] < *minCount)
{
*minCount = frequency[i];
*minChar = i + 65;
}


}

}


int main()
{
LetterCounter lc;
ifstream inFile("c:/letter_count.txt", ios::in);

char minChar, maxChar;
int minCount, maxCount;

minChar = maxChar = minCount = maxCount = 0;

lc.ReadFile("c:/letter_count.txt");

lc.ParseTextAndCountLetters();
lc.getMinMaxChar(&minChar, &maxChar, &minCount, &maxCount);

printf("\n The most common letter is %c with = %d occurrences", maxChar, maxCount);



printf("\nPress a key to exit!!");




getchar();

return 0;
}
Read Full Discussion Thread for this article