2010-02-12 34 views
28

如何使用std::getline函数检查文件结束?如果我使用eof(),它将不会发出eof信号,直到我试图读取超出文件结尾。检查字符串中的eof :: getline

+0

这'不建议eof'是真实的,但出于不同的原因。通过EOF读取*完全是*当您想要测试EOF时做什么,所以'eof'在这方面效果很好。 – 2010-02-12 12:03:41

回答

9

只要阅读,然后检查读操作成功:由于多种原因

std::getline(std::cin, str); 
if(!std::cin) 
{ 
    std::cout << "failure\n"; 
} 

由于故障可能是,你可以使用eof成员函数看到它发生的事情实际上是EOF:

std::getline(std::cin, str); 
if(!std::cin) 
{ 
    if(std::cin.eof()) 
     std::cout << "EOF\n"; 
    else 
     std::cout << "other failure\n"; 
} 

getline返回流,因此您可以更紧凑写:

if(!std::getline(std::cin, str)) 
39

在C++中的经典阅读循环是:

while (getline(cin, str)) { 

} 

if (cin.bad()) { 
    // IO error 
} else if (!cin.eof()) { 
    // format error (not possible with getline but possible with operator>>) 
} else { 
    // format error (not possible with getline but possible with operator>>) 
    // or end of file (can't make the difference) 
} 
+1

这个答案太棒了。如果你需要错误信息,这是唯一的方法。它真的需要花时间来解决这个问题:http://gehrcke.de/2011/06/reading-files-in-c-using-ifstream-dealing-correctly-with-badbit-failbit-eofbit-and-perror/ – 2011-07-06 11:19:09