為什麼在迴圈條件裡使用 iostream::eof 會被認為是錯誤的?
單單是我們的檔案沒有達到 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!
}
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP