1

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

jpw
  • 44,361
  • 6
  • 66
  • 86
  • The method you are using will only work if there is only the words on each line of the file with no leading or trailing spaces and is the exact case of the word is the same. – Galik Aug 23 '15 at 21:45

1 Answers1

2

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>
}
Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • thank you. but my dictionary has each word in an own line – Name_doesnt_matter Aug 23 '15 at 21:37
  • 1
    @Name_doesnt_matter it will work nevertheless, the extraction operator skips whitespaces. The issue with `getline` is that you probably end up reading an additional space (that you may have at the end of each word). – vsoftco Aug 23 '15 at 21:40
  • 1
    Quite possibly a `\r` character if the file has DOS line endings. – Jonathan Wakely Aug 23 '15 at 21:49
  • @JonathanWakely absolutely correct, and highly probable. – vsoftco Aug 23 '15 at 21:50
  • thank you it worked, however it only works if the word in my file and the word I enter have less than 4 characters. – Name_doesnt_matter Aug 23 '15 at 21:53
  • 1
    @Name_doesnt_matter It should work no matter the length, as long as the word itself doesn't contain white spaces (and it shouldn't of course). Make sure you don't have some other issue. – vsoftco Aug 23 '15 at 21:57