Reputation: 33
I can't seem to get this simple code to work. I want to open a text file and compare each line to a word using this function:
ifstream ifs("wordsEn.txt");
bool findword (string word)
{
string currentword="";
if (!ifs.is_open()) {
cout << "error" <<endl;
return false;
}
while(getline(ifs, currentword)) {
if (currentword == word) {
cout<< "true" <<endl;
return true;
}
}
return false;
}
Although this should work, this function never returns true. I know this is very basic but I can't find my mistake
Upvotes: 1
Views: 92
Reputation: 56547
Replace your condition in while
with
while (ifs >> currentword)
and it should work. As you are doing it now, you are reading the whole line, not word by word. If you want to read line by line, you need to further tokenize each line (using e.g. a std::istringstream
).
EDIT 1 Even if you have a single word per line in your file, you have to make absolutely sure that you don't have any additional white spaces before/after it, since if you do, then the string will be something like " word ", and not "word". That's why it's safer to use directly the extraction operator, since by default it skips white spaces.
EDIT 2 The modern C++ way of writing your search function looks more like
bool findword (const std::string& word) {
std::istream_iterator<std::string> it_beg(ifs); // need to #include <iterator>
std::istream_iterator<std::string> it_end{};
return (std::find(it_beg, it_end, word) != it_end); // need to #include <algorithm>
}
Upvotes: 2