為什麼在迴圈條件裡使用 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!
   }
}

更新於: 23-6 月-2020

153 次瀏覽

開啟您的 職業

完成該課程以獲得認證

開始學習
廣告
© . All rights reserved.