简单的c++文件读取使用if流

Simple c++ file reading using if stream

本文关键字:if 读取 c++ 文件 简单      更新时间:2023-10-16

我似乎不能让这个简单的代码工作。我想打开一个文本文件,并使用以下函数将每行与一个单词进行比较:

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

虽然这应该可以工作,但是这个函数永远不会返回true。我知道这是非常基本的,但是我找不到我的错误

while中的条件替换为

while (ifs >> currentword)

,它应该可以工作。你现在读的是整行,而不是一个字一个字地读。如果您想逐行读取,则需要进一步对每行进行标记(例如使用std::istringstream)。

EDIT 1即使你在文件中每行有一个单词,你也必须绝对确保你在它之前/之后没有任何额外的空白,因为如果你这样做,那么字符串将是类似"word"的东西,而不是"word"。这就是为什么直接使用提取操作符更安全,因为默认情况下它会跳过空格。

EDIT 2现代c++编写搜索函数的方式看起来更像

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