Implementing a basic spell-checker using C-style strings and a dictionary involves several steps. We'll create a simple version that checks if a word is in our dictionary. If it's not, we'll consider it misspelled. Here's a step-by-step guide:
First, we need a dictionary. For simplicity, we'll use an array of C-style strings:
#include <cstring>
#include <iostream>
const char* dictionary[] = {
"apple", "banana", "cherry", "date", "elderberry",
"fig", "grape", "honeydew", "kiwi", "lemon"};
const int dictionarySize =
sizeof(dictionary) / sizeof(dictionary[0]);
Next, we'll implement a function to search for a word in our dictionary:
bool isInDictionary(const char* word) {
for (int i = 0; i < dictionarySize; ++i) {
if (strcmp(dictionary[i], word) == 0) {
return true;
}
}
return false;
}
Now, let's create a function that checks the spelling of a word:
void spellCheck(const char* word) {
if (isInDictionary(word)) {
std::cout << word << " is spelled correctly.\n";
} else {
std::cout << word << " might be misspelled.\n";
}
}
Let's put it all together in a main()
 function:
int main() {
char word[50];
while (true) {
std::cout << "Enter a word to check "
"(or 'quit' to exit): ";
std::cin >> word;
if (strcmp(word, "quit") == 0) {
break;
}
spellCheck(word);
}
}
Here's the complete program:
#include <cstring>
#include <iostream>
const char* dictionary[] = {
"apple", "banana", "cherry", "date", "elderberry",
"fig", "grape", "honeydew", "kiwi", "lemon"};
const int dictionarySize =
sizeof(dictionary) / sizeof(dictionary[0]);
bool isInDictionary(const char* word) {
for (int i = 0; i < dictionarySize; ++i) {
if (strcmp(dictionary[i], word) == 0) {
return true;
}
}
return false;
}
void spellCheck(const char* word) {
if (isInDictionary(word)) {
std::cout << word << " is spelled correctly.\n";
} else {
std::cout << word << " might be misspelled.\n";
}
}
int main() {
char word[50];
while (true) {
std::cout << "Enter a word to check "
"(or 'quit' to exit): ";
std::cin >> word;
if (strcmp(word, "quit") == 0) {
break;
}
spellCheck(word);
}
}
This program creates a simple spell-checker that checks if a word is in our dictionary. Here's an example of how it might run:
Enter a word to check (or 'quit' to exit): apple
apple is spelled correctly.
Enter a word to check (or 'quit' to exit): banan
banan might be misspelled.
Enter a word to check (or 'quit' to exit): quit
Remember, this is a very basic spell-checker. Real-world spell-checkers are much more complex, often using techniques like:
Also, when working with strings in C++, it's generally safer and more convenient to use std::string
instead of C-style strings. However, this example demonstrates how you can work with C-style strings if needed.
Answers to questions are automatically generated and may not have been reviewed.
A guide to working with and manipulating C-style strings, using the
library