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

更新於:2020 年 6 月 23 日

152 次瀏覽

開啟您的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.