Tuesday, May 29, 2018

c++ - More about EOF in loop condition

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?

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...