c++ - 从文件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) )
是处理逐行读取直到文件结束的正确方法,请参见例如this question和this one。
推荐阅读
- google-chrome - NET::ERR_CERT_VALIDITY_TOO_LONG - 服务器证书的有效期过长
- sql - 优化 SQL 查询:如何检查一个 Id 是否分配给了比其他 Id 更多的 Id(不应该)
- javascript - UseEffect 不会使用更新的状态
- jenkins - 在 CentOS 7 上安装 Jenkins 时无法启动
- python - 迭代字典时Django模板未检测到某些键
- string - Haskell:字符串中最后两个整数的总和
- r - 如何在创建条件R时使用级别而不是标签
- chat - Mesibo SDK:1对1聊天:语音笔记功能Android
- javascript - 将对象键重命名为不同格式的方法
- javascript - 获取当前 Observable 状态的值