【发布时间】:2011-01-16 02:58:36
【问题描述】:
如何使用std::getline 函数检查文件结尾?如果我使用eof(),它不会发出eof 的信号,直到我尝试读取文件结尾之外的内容。
【问题讨论】:
-
不推荐
eof是真的,但出于不同的原因。当您想要测试 EOF 时,读取过去的 EOF正是您所做的,因此eof在这方面效果很好。
如何使用std::getline 函数检查文件结尾?如果我使用eof(),它不会发出eof 的信号,直到我尝试读取文件结尾之外的内容。
【问题讨论】:
eof 是真的,但出于不同的原因。当您想要测试 EOF 时,读取过去的 EOF正是您所做的,因此 eof 在这方面效果很好。
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)
}
【讨论】:
只需读取,然后检查读取操作是否成功:
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))
【讨论】:
ifstream 有peek() 函数,它从输入流中读取下一个字符而不提取它,只返回输入字符串中的下一个字符。
因此,当指针指向最后一个字符时,它将返回 EOF。
string str;
fstream file;
file.open("Input.txt", ios::in);
while (file.peek() != EOF) {
getline(file, str);
// code here
}
file.close();
【讨论】: