首页 > 解决方案 > 从文件c ++读取时的无限循环

问题描述

尽管我在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;
}

标签: c++infinite-loopfile-handlinggetline

解决方案


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

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

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


同时删除&& !fin.eof(). 它没有任何目的。while ( getline(fin, line) )是处理逐行读取直到文件结束的正确方法,请参见例如this questionthis one


推荐阅读