To get it to print something, try adding \n to the end of the strings at lines 80 & 84 in
spellCheck::checkSpelling()
What is spellCheck::numberOfItems() supposed to do? Right now it returns the number of items in the bucket for word. So when you call it inside main(), it's basically saying "if there is already a word in this word's bucket, then don't bother to add this word." If I remove the call to numberOfItems, so that every word in the dictionary gets inserted into the hash table, then the program works for me.
This should be enough to get the program working. Once it's working, you might want to consider these additional changes. Be sure to save the working version before attempting to do any of this.
The constructor is still putting the string "empty" in each bucket. There's no need for that. Just initialize all of the pointers to nullptr.
It may be personal preference, but I prefer a for() loop when going through a linked list. That way all of the "loop" logic is in one place, and all of the "what to do inside the loop" is in another. When you use a while loop, the logic for is all over the place. Compare this:
1 2 3 4 5
|
item *Ptr = hashtbl[index];
while (Ptr->next != NULL) {
count++;
Ptr = Ptr->next;
}
|
to this:
1 2 3
|
for (item *Ptr = hashtbl[index]; Ptr->next != nullptr; Ptr = Ptr->next) {
count++;
}
|
In the second case, the
for
loop makes it clear that you're walking through each item in the list.
Look at
checkSpelling()
. Right now it takes a word and tells you whether it's spelled correctly. Now suppose you're asked to modify the program so that it reads a file and prints out the number of misspelled words. You can't reuse checkSpelling() without modifying it.
This is why it's always a good idea to separate
computation (computing an answer of some sort) from
presentation (displaying the results of the answer). In this case, checkSpelling() should just return bool to indicate whether the word is spelled correctly, and the main program should print the appropriate results based on that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
// Return true if the string s is spelled correctly, otherwise false.
bool
spellCheck::checkSpelling(std::string s)
{
int itemsearch = hash(s);
bool correct = false;
std::string word;
for (item *Ptr = hashtbl[itemsearch]; Ptr != nullptr; Ptr = Ptr->next) {
if (Ptr->word == s) {
return true;
}
}
return false;
}
...
int main()
{
...
std::string s;
std::cin >> s;
if (hashObject.checkSpelling(s)) {
std::cout << "Spelled Correctly.\n"; // dmh
} else {
std::cout << "Spelled incorrectly:\n"; // dmh
}
}
|
Modifying
this program to print the number of misspelled words in a file would be almost trivial.