我如何使用 std::getline
函数检查文件结尾? 如果我使用 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();