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

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

我有以下一段代码:

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

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

一些非常相似的事情发生在:

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

你非常非常不想检查坏的,自由的和好的。 特别是对于eof(如!stream.eof()是一个常见的错误),当前处于EOF的stream并不一定意味着上一次input操作失败; 相反,不在EOF并不意味着最后的input是成功的。

所有的stream状态函数 – 失败,不好,自由和好 – 告诉你stream的当前状态,而不是预测未来操作的成功。 在所需的操作之后检查stream本身(相当于一个反向失败检查):

 if (getline(stream, line)) { use(line); } else { handle_error(); } if (stream >> foo >> bar) { use(foo, bar); } else { handle_error(); } if (!(stream >> foo)) { // operator! is overloaded for streams throw SomeException(); } use(foo); 

阅读和处理所有行:

 for (std::string line; getline(stream, line);) { process(line); } 

指出,好()是错误的,不等同于testingstream本身(上面的例子)。

只是使用

 ifstream f("x.txt"); while (getline(f, line)) { // whatever } 

这是编写这种循环的惯用方式。 我一直无法重现错误(在Linux机器上)。

它没有读取最后一行两次,而是因为它到达eof时没有读取,所以你的string行有它以前的值。

这是因为当读取EOF时,f不再是“好的”,而不是当它正在阅读时。