而循环停止太晚与EOF检查

while loop stops too late with eof check

本文关键字:EOF 检查 循环      更新时间:2023-10-16

我必须读取一个文件,其中包含存储在向量中的路径列表。

    vector<string> files;
    ifstream in;
    string x;
    while( !in.eof() ) {
       in >> x;
       files.push_back(x);
    }

但问题是,当读取最后一个路径时,eof() 仍然是假的,循环继续执行另一个不需要的步骤。修复可能是这样的事情

    vector<string> files;
    ifstream in;
    string x;
    while( in >> x ) {
       files.push_back(x);
    }

但我认为在 while 循环中代码更复杂的情况下,这不是一个很好的解决方案。我错了吗?

这将允许您读取到文件的末尾,而不是进一步。只要文件中有文本,就会读取每一行。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
 string line;
 ifstream myfile ("example.txt");
 if (myfile.is_open())
 {
   while ( getline (myfile,line) )
   {
     cout << line << 'n';
   }
   myfile.close();
 }
 else cout << "Unable to open file"; 
 return 0;
}