Thursday, 24 November 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...