Write a program that implements a simple spell checker in C++. The spell checker
ID: 3531711 • Letter: W
Question
Write a program that implements a simple spell checker in C++. The spell checker should work as follows: prompt the user to enter a file name to spell check, and then the program will parse the file and check if there are any tokens that are not in the dictionary. Any words that are not found in the dictionary will be printed on the screen. Note that you do not need to worry about sorting words or prompting the user for corrections.
There will be two files, a text file (name input by user) and a dictionary file to compare words with. The text file contains punctuation.
Only <iostream>, <fstream>, <string> can be included.
To search properly, you need to remove punctuation marks (i.e. ( , :
Explanation / Answer
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <stdio.h>
#include <ctype.h>
using namespace std;
const int LENGTH=30;
int BinarySearch (char ary[][LENGTH], int size, char search_item[LENGTH]);
int main ()
{
int n=0, l=0, w=0, pos;
//const int LENGTH=30;
char dict[15000][LENGTH];
char word[LENGTH+1];
char c;
ifstream fin;
fin.open ("dictionary.txt");
for (int len=0; len<=LENGTH; len++)
word[len]=NULL;
if (fin.fail())
{
cout << "Cannot find dictionary file" << endl;
}
// The next chunk reads in the file "dictionary" into a char array
for (n=0; !fin.eof(); n++)
{
fin.getline(dict[n],LENGTH);
}
fin.close();
//for (l=0; l<n; l++)
// cout << dict[l] << endl;
ifstream letter;
letter.open ("letter.txt");
if (letter.fail())
{
cout << "Cannot find draft file" << endl;
}
// Here is where I try and read in the test letter one word at a time,
// then make each letter in the word lowercase before I search for the
// word using the BinarySearch function.
for (l=0; !letter.eof(); l++)
{
letter >> word;
for (int a=0; word[a]!=NULL; a++)
{
while (word[a])
{
c=word[a];
word[a]= (tolower(c));
a++;
}
}
pos=BinarySearch(dict, n, word);
if (pos==-1)
{
cout << word << " misspelled!!" << endl;
}
}
letter.close();
return 0;
}
int BinarySearch (char ary[][LENGTH], int size, char search_item[LENGTH])
{
int first = 0, last = size-1;
bool found = false;
int position = -1, middle;
while (!found && first <= last)
{
middle = (first + last) / 2;
if ((strcmp(ary[middle], search_item))==0)
{
position = middle;
found = true;
}
else if (ary[middle] < search_item)
first = middle+1;
else last = middle-1;
}
return position;
}
//For the dictionary comparing
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.