简体   繁体   中英

Simple c++ file reading using if stream

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

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 eg 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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM