尽管我检查了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) )
是一种处理逐行读取直到文件结束的正确方法,请参见例如this question和this one。
关于c++ - 从文件C++读取时发生无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436846/