而循环停止太晚与EOF检查
while loop stops too late with eof check
我必须读取一个文件,其中包含存储在向量中的路径列表。
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;
}
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- C++模板来检查友元函数的存在
- 如何确定我已使用非编码文件到达 EOF?
- 检查输入是否不是整数或数字
- 试图让变量检查数组中的某些内容
- 检查值是否在集合p1和p2中,但不在p3中
- C++概念:如何使用'concept'检查模板化结构的属性?
- 概念TS检查忽略私有访问修饰符
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- 如何在C++中检查2D数组中负值的输入验证
- C++:正在检查LinkedList中的回文-递归方法-错误
- 使用for循环检查数组中的重复项
- 如何检查一个c++字符串中有多少相同的字符/数字
- 检查不带转换的扫描格式
- 如何使用 istream::ignore() 函数时检查 EOF 条件
- 在getline上检查eof()有什么区别,即while(!getline().eof())和简单地检查while(ge
- 如何在使用ifstream读取txt文件时检查EOF
- 而循环停止太晚与EOF检查
- C++:std::istream 检查 EOF 而不读取/使用令牌/使用运算符>>