Witam,
mam do wykonania program, mający za zadanie zliczenie częstotliwości występowania słów w dowolnym pliku oraz i ich wypisanie. Całość później ograniczyć do 10 najczęściej występujących.
Dla przykładu mam następujące słowa: "aa ab bb aa bb bb". Wynik powinien być następujący:
aa 2
ab 1
bb 3
U mnie niestety wygląda on tak:
aa 2
aa 2
ab 1
bb 3
bb 3
bb 3
Czyli, każde słowo, które ma więcej powtórzeń zostanie wypisane kilkukrotnie. Przypuszczam, iż błąd leży po stronie porównywania dwóch tablic, ale nie mam obecnie pomysłu na inne rozwiązanie. Poniżej przedstawiam kod całego programu.
Dodam, iż nie mogę korzystać z biblioteki map, vector itp.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
struct wordCount
{
string word;
int count;
};
class wordFrequency
{
public:
int countFile(int counter);
void openFile(ifstream &inFile, ofstream &outFile);
void periods(string arr[], int n);
void bubbleSort(string arr[], int n);
private:
string wordsM[];
};
int main()
{
wordFrequency word;
int length;
int counter;
length = word.countFile(counter);
string wordsM[length];
struct wordCount wordFreq[length];
ifstream inFile;
ofstream outFile;
word.openFile(inFile, outFile);
while (!inFile.eof())
{
for(int i=0; i < length; i++)
{
inFile >> wordsM[i];
word.periods(wordsM, length);
wordFreq[i].word = wordsM[i];
wordFreq[i].count = 0;
}
}
word.bubbleSort(wordsM , length);
for (int i = 0; i < length;i++)
{
for (int j = 0; j < length; j++)
{
if (wordsM[i] == wordFreq[j].word)
{
wordFreq[i].count++;
}
}
cout << wordsM[i] << " " << wordFreq[i].count <<endl;
}
inFile.close();
outFile.close();
system ("Pause");
return 0;
}
int wordFrequency::countFile(int counter)
{
ifstream inFile;
int counts = 0;
string str;
inFile.open("input.txt");
while (!inFile.eof())
{
inFile >> str;
counts++;
}
return counts;
}
void wordFrequency::openFile(ifstream &inFile, ofstream &outFile)
{
inFile.open("input.txt");
}
void wordFrequency::periods(string arr[], int n)
{
int i;
size_t found;
for ( i = 0; i < n; i++)
{
found=arr[i].find('.');
if (found!=string::npos)
{
arr[i].replace(arr[i].find('.'),1,"");
}
found = arr[i].find(',');
if (found!=string::npos)
{
arr[i].replace(arr[i].find(','),1,"");
}
found = arr[i].find('"');
if (found!=string::npos)
{
arr[i].replace(arr[i].find('"'),1,"");
}
found = arr[i].find('-');
if (found!=string::npos)
{
arr[i].replace(arr[i].find('-'),1,"");
}
found = arr[i].find('!');
if (found!=string::npos)
{
arr[i].replace(arr[i].find('!'),1,"");
}
}
}
void wordFrequency::bubbleSort(string arr[], int n)
{
int i, j;
string temp;
for ( i = 1; i < n; i++)
{
for (j = 0; j < n - i; j++)
{
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}