从文件中删除特定行 [英] Deleting specific line from file

查看:102
本文介绍了从文件中删除特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我的示例文件的内容:

These are the contents of my example file:

abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA FIND ME akjsdkjhwjkjhasfkajbsdh ADHKJAHSHSDJH

我需要在文件内部查找并删除查找我,以便输出如下所示:

I need to find and delete the 'FIND ME' inside of the file so the output would look like this:

abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH

我尝试了以下方法来进行getline,然后全部写入

I have tried the following method of doing getline and then writing all of the contents except the FIND ME into a temporary file and then rename the temporary file back.

string deleteline;
string line;

ifstream fin;
fin.open("example.txt");
ofstream temp;
temp.open("temp.txt");
cout << "Which line do you want to remove? ";
cin >> deleteline;



while (getline(fin,line))
{
    if (line != deleteline)
    {
    temp << line << endl;
    }
}

temp.close();
fin.close();
remove("example.txt");
rename("temp.txt","example.txt");

,但是它不起作用。
就像一个旁注:该文件没有换行符/换行符。因此文件内容全部写在1行中。

but it doesn't work. Just as a side note: the file has NO newline/linefeeds. So the file contents are all written in 1 line.

编辑:

固定代码:

while (getline(fin,line))
{
    line.replace(line.find(deleteline),deleteline.length(),"");
    temp << line << endl;

}

这给了我预期的结果。谢谢大家的帮助!

This gets me the results I expected. Thank you everyone for helping!

推荐答案

尝试一下:

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

这篇关于从文件中删除特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆