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

标签 c++ infinite-loop file-handling getline

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

相关文章:

c++ - C++ 中的 upper_bound/lower_bound 函数

c++ - 如何 boost boost interval_map 查找的性能

Java:无限while循环中的If语句

c++ - 来自 Qt C++ 应用程序的 Octave 图

C++使用进程名称获取窗口标题

java - 如何使用 Scanner 处理无效输入(InputMismatchException)引起的无限循环

SQL-Server 无限循环

c - 如何列出 C 目录中目录中的文件?

c - 如何从C中的整数和字符串文件中读取整数

c - fscanf 无法从 txt 文件读取数据