루프의 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!
}
}