iostream::eof ในลูปถือว่าผิดเพราะเรายังไม่ถึง EOF ไม่ได้หมายความว่าการอ่านครั้งต่อไปจะสำเร็จ
เมื่อเราต้องการอ่านไฟล์โดยใช้ไฟล์สตรีมในภาษา C++ และเมื่อเราใช้ลูปเพื่อเขียนไฟล์ หากเราตรวจสอบจุดสิ้นสุดของไฟล์โดยใช้ stream.eof() เรากำลังตรวจสอบว่าไฟล์นั้นถึงจุดสิ้นสุดหรือไม่
โค้ดตัวอย่าง
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myFile("myfile.txt");
string x;
while(!myFile.eof()) {
myFile >> x;
// Need to check again if x is valid or eof
if(x) {
// Do something with x
}
}
} เมื่อเราใช้สตรีมโดยตรงในลูป เราจะไม่ตรวจสอบเงื่อนไขอีก
โค้ดตัวอย่าง
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myFile("myfile.txt");
string x;
while(myFile >> x) {
// Do something with x
// No checks needed!
}
}