gpt4 book ai didi

c++ - 从文件C++读取时发生无限循环

转载 作者:行者123 更新时间:2023-12-01 15:05:23 24 4
gpt4 key购买 nike

尽管我检查了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 questionthis one

关于c++ - 从文件C++读取时发生无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com