c++ - while 循环因 eof 检查停止得太晚

标签 c++ loops while-loop fstream eof

<分区>

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

    vector<string> files;
    ifstream in;
    string x;

    while( !in.eof() ) {
       in >> x;
       files.push_back(x);
    }

但问题是,当读取最后一条路径时,in.eof() 仍然是 false 并且循环继续进行另一个不需要的步骤。 修复可能是这样的

    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;
}

关于c++ - while 循环因 eof 检查停止得太晚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22797524/

相关文章:

c++ - 在 C++ 中迭代一个字符串并填充一个数组

java - 在 while 循环中运行多次迭代

Python - 虽然为真 : Try Except Else - Program Flow Question

C++ 运行时对象指针的优先级队列错误为无效堆

c++ - 访问另一个类的指针数组的类的成员

c++ - 这个来自 Effective Modern C++ 的项目仍然是最新的吗?

python - 如何使用 for 循环对一组数据帧运行操作?

c++ - 调用GetPrinterDataFromPort时CriticalSection崩溃

php - wordpress循环无法完成posts的查询

bash - 如何使用 while read line with tail -n