เพียงเพราะเรายังไม่ถึง EOF ไม่ได้หมายความว่าการอ่านครั้งต่อไปจะสำเร็จ
พิจารณาว่าคุณมีไฟล์ที่คุณอ่านโดยใช้สตรีมไฟล์ใน C++ เมื่อเขียนลูปเพื่ออ่านไฟล์ หากคุณกำลังตรวจสอบ stream.eof() แสดงว่าคุณกำลังตรวจสอบว่าไฟล์มาถึง 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!
}
}