Your main issue is you seem to want to step through the quote using i
, but at the same time you are using it to index Words
. A more logical way to do things is to check each word of the quote against the existing words you have already copied into Words
, and either incrementing the count or inserting the word accordingly. You can also take advantage of the fact that there will be at most NumWords
in Words
and allocate enough memory at the start of the function:
void CountWords(char const** Quote, char**& Words, int*& Count, int NumWords)
{
Words = new char*[NumWords];
Count = new int[NumWords];
int words = 0;
for (int i = 0; i < NumWords; ++i) {
int j = 0;
for (; j < words; ++j) {
if (!strcmp(Quote[i], Words[j])) { // Duplicate word
++Count[j];
break;
}
}
if (j == words) { // New word found
Words[words] = new char[strlen(Quote[i]) + 1]{};
strcpy(Words[words], Quote[i]);
Count[words] = 1;
words++;
}
}
Count[words] = 0;
}
int main()
{
char const* quote[] = {"Hello", "world", "hello", "world"};
char** words;
int* count;
CountWords(quote, words, count, 4);
for (int i = 0; count[i]; ++i) {
std::cout << words[i] << ' ' << count[i] << '\n';
delete[] words[i];
}
delete[] words;
delete[] count;
}
In any case array / pointer shenanigans are hard to read and error-prone, there is hardly any code here (or your original code) that could be called "c++" aside from new
, it's c with a dash of c++. The entire app can be more easily written in modern c++ like this:
#include <iostream>
#include <unordered_map>
int main()
{
std::string word;
std::unordered_map<std::string, int> map;
while (std::cin >> word)
++map[word];
for (auto const& w : map)
std::cout << w.first << " : " << w.second << '\n';
}
And used like this: app < textfile.txt