Aql*_*jid 1 c++ getline infinite-loop file-handling
虽然我检查了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;
}
Run Code Online (Sandbox Code Playgroud)
您在评论中声称temp应该引用临时文件,但事实并非如此。您打开相同的文件进行追加,您已经使用fin.
由于您在迭代循环时不断追加,因此文件中总会有新内容要读取,从而导致无限循环(直到磁盘空间用完)。
为您的temp流使用不同的文件名并稍后重命名(如评论所述)。
同时删除&& !fin.eof(). 它没有任何意义。while ( getline(fin, line) )是处理逐行读取直到文件结束的正确方法,请参见例如this question和this one。