相关疑难解决方法(0)

测试stream.good()或!stream.eof()读取最后一行两次

可能重复:
为什么循环条件中的iostream :: eof被认为是错误的?

我有以下代码:

ifstream f("x.txt");
string line;
while (f.good()) {
  getline(f, line);
  // Use line here.
}
Run Code Online (Sandbox Code Playgroud)

但这会两次读到最后一行.为什么会发生这种情况,我该如何解决?

与以下情况非常相似:

ifstream f("x.txt");
string line;
while (!f.eof()) {
  getline(f, line);
  // Use line here.
}
Run Code Online (Sandbox Code Playgroud)

c++ iostream

17
推荐指数
2
解决办法
3万
查看次数

标签 统计

c++ ×1

iostream ×1