您好!您提到的 ifstream object.eof()
不起作用,这是一个 C++ 中的问题。在 C++ 中,ifstream
对象的 eof()
函数用于检测文件是否已经到达结尾。但是,当您尝试使用 object.eof()
时,可能会遇到一些问题。
这是因为 eof()
函数只能检测到文件的结尾,但不能检测到文件的开头。因此,在读取文件时,如果您希望检测文件是否已经到达结尾,应该在读取操作之后再调用 eof()
函数。例如:
#include<iostream>
#include <fstream>
int main() {
std::ifstream input_file("example.txt");
int data;
while (input_file >> data) {
std::cout << "Read data: "<< data<< std::endl;
}
if (input_file.eof()) {
std::cout << "End of file reached."<< std::endl;
} else {
std::cout << "Error occurred while reading the file."<< std::endl;
}
input_file.close();
return 0;
}
在上面的代码中,我们首先打开文件并尝试读取数据。当文件读取完毕时,我们再调用 eof()
函数来检测文件是否已经到达结尾。如果文件已经到达结尾,则输出 "End of file reached.",否则输出 "Error occurred while reading the file."。
希望这个答案能够帮助您解决问题!
没有搜到相关的文章