I need to search for a word in a file and return if its in the file or not, but i'm not sure how to manipulate this code to do so, (this is from my teacher and this is what he told us to do) the file is in alphabetical order already as well and i do not know how to write a binary search at all.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
usingnamespace std;
bool openfile(ifstream &handle, string path);
bool search(const vector<string>& v_word, const string& word);
int main(void)
{
vector<string> v_word; // Declare a vector for the dictionary
string word;
vector<string>::iterator it;
ifstream dictionary;
string filename;
unsignedint j = 0, k = 0;
cout << "Enter the full path for the file you want to open" << endl;
getline(cin, filename);
if (!openfile(dictionary, filename))
return 1;
// Now go through the whole dictionary and read in the words
while (!dictionary.eof())
{
dictionary >> word;
//cout << word << endl;
v_word.push_back(word);
k++;
}
cout << "There are " << k << " words in the dictionary." << endl << endl;
cout << "Enter a word to look up in the dictionary." << endl;
cin >> word;
// Now search if word is in dictionary
cout << endl << endl << endl;
system("pause");
return 0;
}
bool openfile(ifstream &handle, string path)
{
// handle.open("C:/Temp/dictionary_four_letter_words.txt");
handle.open(path);
if (!handle)
{
cout << "Unable to open file" << path << endl;
system("pause");
returnfalse;
}
else
{
cout << path << " Opened" << endl << endl;
}
returntrue;
}
bool search(const vector<string>& v_word, const string& word)
{
vector<string> v_word; // Declare a vector for the dictionary
string word;
vector<string>::iterator it;
if (search(v_word, word)){
word = v_word;
cout << " Word was found" << endl;
}
// found
else{
cout << " Word not in dictionary" << endl;
}
// not found
return word;
}