测试stream.good()或!stream.eof()读取最后一行两次 [英] Testing stream.good() or !stream.eof() reads last line twice
问题描述
我有以下代码:
ifstream f("x.txt");
string line;
while (f.good()) {
getline(f, line);
// Use line here.
}
但这会读取最后一行两次。为什么会发生这种情况,我该如何解决?
But this reads the last line twice. Why does this happen and how do I fix it?
发生类似的情况:
ifstream f("x.txt");
string line;
while (!f.eof()) {
getline(f, line);
// Use line here.
}
推荐答案
检查坏,eof和好。特别是对于eof(因为!stream.eof()是一个常见的错误),当前处于EOF的流不一定意味着最后一个输入操作失败;相反,不是在EOF不意味着最后一个输入成功。
You very, very rarely want to check bad, eof, and good. In particular for eof (as !stream.eof() is a common mistake), the stream currently being at EOF does not necessarily mean the last input operation failed; conversely, not being at EOF does not mean the last input was successful.
所有流状态函数 - fail,bad,eof和good - 告诉你current而不是预测未来操作的成功。在所需操作之后检查流本身(相当于反向失败检查):
All of the stream state functions – fail, bad, eof, and good – tell you the current state of the stream rather than predicting the success of a future operation. Check the stream itself (which is equivalent to an inverted fail check) after the desired operation:
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);
}
有人指出,good()被错误命名,并不等同于测试流本身(上面的例子)。
Pointedly, good() is misnamed and is not equivalent to testing the stream itself (which the above examples do).
这篇关于测试stream.good()或!stream.eof()读取最后一行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!