【发布时间】: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 >> text;可能会失败,而您永远不会知道它,因为您从不检查它。因此,您将继续前进并使用text中发生的任何废话,可能最后一次成功。您是否尝试在文件中搜索 last 单词? -
可以,正常输出
标签: c++