為什麼迴圈條件內的 iostream::eof 被認為是錯誤的?


在迴圈中使用 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!
   }
}

更新於: 30-Jul-2019

152 次瀏覽

開啟你的 事業

透過完成課程取得認證

開始
廣告