从文件 C++ 读取时的无限循环

infinite loop while reading from a file c++

本文关键字:无限循环 读取 文件 C++      更新时间:2023-10-16

尽管我在while条件下检查了EOF,但while循环运行了无限次。但它仍然运行了无限次。下面是我的代码:

int code;
cin >> code;
std::ifstream fin;
fin.open("Computers.txt");
std::ofstream temp; // contents of path must be copied to a temp file then renamed back to the path file
temp.open("Computers.txt", ios_base::app);

string line;
string eraseLine = to_string(code);
while (  getline(fin, line) && !fin.eof() ) {
if (line == eraseLine)
{
/*int i = 0;
while (i < 10)
{*/
temp << "";
//i++;
//}
}
if (line != eraseLine) // write all lines to temp other than the line marked for erasing
temp << line << std::endl;
}

您在评论中声称temp应该引用临时文件,但事实并非如此。打开同一文件进行追加,您已经使用fin从中读取。

由于您在迭代循环时不断追加,因此文件中总会有新内容需要读取,从而导致无限循环(直到磁盘空间用完为止(。

为您的temp流使用不同的文件名,稍后再重命名(如评论所述(。


同时删除&& !fin.eof()。它没有任何用处。while ( getline(fin, line) )是处理逐行阅读直到文件末尾的正确方法,请参阅例如这个问题和这个问题。