从文件 C++ 读取时的无限循环
infinite loop while reading from a file 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;
}
您在评论中声称temp
应该引用临时文件,但事实并非如此。打开同一文件进行追加,您已经使用fin
从中读取。
由于您在迭代循环时不断追加,因此文件中总会有新内容需要读取,从而导致无限循环(直到磁盘空间用完为止(。
为您的temp
流使用不同的文件名,稍后再重命名(如评论所述(。
同时删除&& !fin.eof()
。它没有任何用处。while ( getline(fin, line) )
是处理逐行阅读直到文件末尾的正确方法,请参阅例如这个问题和这个问题。
相关文章:
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 从文件 C++ 读取时的无限循环
- C++:从文件中读取x y数据会产生无限循环吗
- 在控制台上输出我从文件中读取的整数,将程序插入无限循环
- CPP 在读取结构数据时无限循环错误?
- 当要读取的文件已打开时,文件读取进入无限循环
- 将结构从二进制文件读取到链表,导致无限循环
- 为什么这段代码最终会进入一个无限循环,读取std::cin
- C++ 无限循环读取文件创建重定向命令输出
- 在 c++ 中从文件读取时会发生无限循环
- 使用 cin::fail() 从 stdin 进行无限循环读取
- 读取输入文件时的无限循环
- cin在读取非数值时无限循环
- 读取 stdio.h 时的无限循环
- 读取文件时进入无限循环
- 从文件中读取信息后,会发生一个无限循环
- c++ -读取文件字符时的无限循环
- 从文件读取导致无限循环的问题
- 从文件中读取整数时的无限循环
- 当check为eof时,使用getline读取文本文件会导致无限循环