用C++从txt文件中删除特定行找不到问题

问题描述

您好,我正在尝试完成我的程序,我需要它从文本文件删除一行。我尝试了其他人的多个代码,试图找出为什么我的 temp.txt 文件不会重命名和替换我的fruit.txt 文件,这是我从中删除一行的文件。任何帮助将不胜感激。

主要

error[E0515]: cannot return value referencing local variable `string`
  --> src/main.rs:27:5
   |
23 |     let lines: Split<&str> = string.split("\n");
   |                              ------ `string` is borrowed here
...
27 |     v
   |     ^ returns a value referencing data owned by the current function

文件处理.h

#include <iostream>
#include "filehandling.h"

using namespace std;

int main()
{
    program run;
    run.askUser();
    return 0;
}

解决方法

问题是你有out_stream.open ("fruit.txt");,但是你直到程序结束才关闭它,所以你不能remove()一个打开的文件。您应该始终测试文件操作的返回值,例如 in the example here

,

一般来说,您不能“删除一行”,而是在没有您不再需要的数据的情况下重写文件。

如果您不再需要的数据恰好是一行文本,那么生成的文件将显示该行已删除。

,

试试:

 line.replace(line.find(eraseFruit),eraseFruit.length(),"");

http://www.cplusplus.com/reference/string/string/find/

您也可以尝试擦除。虽然我不确定这是否会有所帮助。

http://www.cplusplus.com/reference/string/string/erase/

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...