Search a vector for a word (string)

I need to open a word list file, read it into a vector, then search the vector to see if a given word is in the file. I have most, but am having trouble with searching the vector, namely the Search function in the code below:


#include <iostream>
#include <string>
#include <vector>
#include <fstream>


using namespace std;

void ShowMenu();
vector <string> GetWords();
bool Search ( vector <string>, string );


int main()
{
ShowMenu();

return 0;
}

void ShowMenu()
{
int menuChoice;
string word;
do
{
if (!cin.good())
{
cin.clear();
cin.ignore();
}
cout << "Menu: " << endl;
cout << "\t1.) Check Word" <<endl;
cout << "\t2.) Exit" <<endl;

cin >> menuChoice;
//}while (!cin.good());

if (menuChoice==1)
{
cin >> word;
// cout << "Checking word..."; //open file check for word....
vector<string> One;
One=GetWords();
cout << Search(One, word) <<endl;
}

}while(menuChoice!=2);
return;
}

vector<string> GetWords()
{
vector<string> words;
string word;
ifstream myfile;

myfile.open("WordList", ios::in);

if (myfile.is_open())
{
while (!myfile.eof())
{
myfile >> word;
words.push_back(word);
}
}
myfile.close();
return words;
}

bool Search( vector<string> words, string word)
{

for (int i=0; i<words.size(); i++)
{
if (words[i] == word)
{
return true;
}
else
{
return false;
}
}
}

Just go through your code as it would be executed. First time into loop, i=0, so you compare words[0] with word, and if it matches you return true, and if doesn't match, you return false; end of function. Is that correct behavior?

That's what I have (last function) but it will only return true if the word being searched is the first word. If the word is later in the file(vector) it will return false. I don't know how to start somewhere other than postition zero after words[0] returns false.
Last edited on
Topic archived. No new replies allowed.