struct Word
{
Word(){}
Word(const std::string &str) :
word(str), count(1)
{
}
std::string word;
int count;
};
void Sort(Word arr[], int size)
{
for (int i = 0; i < size - 1; ++i)
{
for (int j = size - 2; j >= i; --j)
{
if (arr[j].count < arr[j + 1].count)
{
std::swap(arr[j], arr[j + 1]);
}
}
}
}
size_t Find(const Word* arr, int n, const std::string& match)
{
for(int i = 0; i < n; ++i)
if(arr[i].word == match)
return i;
return -1;
}
void main(void)
{
Word arr[32];
std::string text;
int n = 0;
char buff[128];
FILE *f = fopen("file.txt", "r");
if (f != nullptr)
{
while (!feof(f))
{
fgets(buff, sizeof(buff), f);
text += buff;
text += " ";
}
fclose(f);
char* ptr = strtok(const_cast<char*>(text.c_str()), " ,-.\n\r\t");
while (ptr != nullptr)
{
if (n < sizeof(arr) / sizeof(Word))
{
if (Find(arr, n, ptr) == -1)
{
arr[n++] = Word(ptr);
}
else
{
arr[Find(arr, n, ptr)].count++;
}
ptr = strtok(nullptr, " ,-.\n\r\t");
}
}
Sort(arr, n);
printf("%-20s | %s\n", "Word", "Quantity");
printf("-------------------------------\n");
for (int i = 0; i < n; ++i)
printf("%-20s | %d\n", arr[i].word.c_str(), arr[i].count);
//std::cout << arr[i].word << " = " << arr[i].count << "\n";
}
getchar();
}
Comments