Okay, when I saw this thread: Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
I read the answers but I really didn't understand what is wrong in this, maybe because I don't have much experience in c++ but my code works exactly the way it's supposed to.
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();
}
I enter in a word, and it searches for it in a text file, and I had zero problems using that. So, when is this condition considered wrong?
file >> text;
can fail and you never know it because you never check it. You would thus march on and use whatever crap happens to be intext
, potentially the last time is succeeded.Did you try searching for the last word in your file? – WhozCraig