I am making a spellcheck program that compares words from a notepad file to another notepad dictionary file. I just need a bit of help in the binary search algorithm. How exactly do I report that there is a spelling mistake? How do I return a 0 or 1 from my function. I'm just slightly confused here.
#include <iostream>
#include <fstream>
#include <cstring>
usingnamespace std;
int spellcheck(char dict[][20], char wordfromletter[20], int sizeoffile) // Binary search function that takes in the current word, the dictionary array, and the size of the dictionary.
{
int first = 0;
int last = sizeoffile - 1;
int middle = (first + last) / 2;
bool correct = false;
while ((strcmp(dict[middle], wordfromletter)) != 0 && first <= last)
{
if (strcmp(dict[middle], wordfromletter) > 0)
{
first = middle + 1;
}
else
{
last = middle - 1;
}
middle = (first + last) / 2;
}
if () // This is where I just need help. I don't know how to know whether there is a spelling mistake or not.
return 1;
elsereturn 0;
}
int main() {
ifstream input1;
ifstream input2;
char dict[200][20];
char wordfromletter[20];
int correction = 0;
int sizeoffile = 0;
input1.open("dictionary.txt");
input2.open("letter.txt");
if (input1.fail()) {
cout << "error opening file" << endl;
system("Pause");
return 0;
}
if (input2.fail()) {
cout << "error opening letter" << endl;
system("Pause");
return 0;
}
for (int n = 0; !input1.eof(); n++)
{
input1 >> dict[n];
++sizeoffile;
}
/*
Printing out the dictionary
for (int p = 0; p < 20; p++)
{
cout << dict[p] << endl;
}
*/
while (!input2.eof())
{
input2 >> wordfromletter;
correction = spellcheck(dict, wordfromletter, sizeoffile);
if (correction == 0)
{
cout << wordfromletter << " spelling mistake" << endl;
}
}
input1.close();
input2.close();
system("pause");
}
Why are you returning integers? It makes more sense to return bool. 1 for found and 0 for not found, right?
Anyways, here's a little snippet of code from a similar binary search. In this case, the person was searching through a Set class and returning an iterator. But in principle they are attempting to do the same thing as you are.