【问题标题】:More about EOF in loop condition更多关于循环条件中的 EOF
【发布时间】:2019-10-27 21:11:38
【问题描述】:

好的,当我看到这个帖子时:Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?

我阅读了答案,但我真的不明白这有什么问题,可能是因为我在 c++ 方面没有太多经验,但我的代码完全按照预期的方式工作。

int main()
{
    ifstream file;
    string text, search;
    int offset;
    cout << "Enter a word: "; cin >> search;
    file.open("Find.txt");
    if (file.is_open()) {
        while (!file.eof()) {
            file >> text;
            offset = text.find(search, 0);
            if (offset != string::npos) {
                cout << text << endl;
            }
        }
    }
    else {
        cout << "Error!";
        return 0;
    }
    file.close();
}

我输入了一个单词,它会在一个文本文件中搜索它,我在使用它时遇到了零问题。那么,这种情况何时被认为是错误的?

【问题讨论】:

  • 因为file &gt;&gt; text; 可能会失败,而您永远不会知道它,因为您从不检查它。因此,您将继续前进并使用 text 中发生的任何废话,可能最后一次成功。您是否尝试在文件中搜索 last 单词?
  • 可以,正常输出

标签: c++


【解决方案1】:

我不会重复该线程中所说的所有内容;那将是浪费时间。

如果你这样做了:

    while (!file.eof()) {
        file >> text;
        // offset = text.find(search, 0);
        // if (offset != string::npos) {
            cout << "Text: " << text << endl;
        // }
    }

...然后您会看到问题:每次运行程序时都会进行一次“额外”循环迭代,text 具有前一次迭代的任何值。

由于您的输出取决于在text 中搜索特定子字符串的结果,如果在输入的最后一行搜索将失败,您就可以逃脱!但是,如果最后一行匹配,您将再次看到问题。

这种循环输入方式总是不会导致错误。这就是为什么链接的问答说它“几乎肯定是错误的”。有时循环内的逻辑是专门为正常工作而设计的;其他时候它恰好发生以避免错误,就像你的那样。

正确的代码是:

while (file >> text)
{
    offset = text.find(search, 0);
    if (offset != string::npos) {
        cout << text << endl;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-19
    • 2015-05-23
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多