【问题标题】:How to delete a specific line in a text file in c++如何在 C++ 中删除文本文件中的特定行
【发布时间】:2019-12-12 06:47:01
【问题描述】:

我正在尝试使用 c++ 删除文本文件中的一行。例如,我有一个包含文本的 .txt 文件:

booking.txt

1 jer 34 r er
2 43 45 34 456
3 2 4 5 6
4 45 546 435 34
5 cottage 1 323 23
6 we we r we
7 23 34 345 345
8 wer wer wer we

我想在满足某个条件时删除一行。假设我要删除第 3 行,id 为 3 的行必须从 .txt 文件中删除。

我的代码:

void DeleteLine(string filename)
{
    string deleteline;
    string line;

    ifstream fin;
    fin.open(filename);
    ofstream temp;
    temp.open("temp.txt");
    cout << "Input index to remove [0 based index]: "; //input line to remove
    cin >> deleteline;

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

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

但给了我以下结果:

1 jer 4 r er
2 4 45 34 456
 2 4 5 6
4 45 546 45 34
5 cottage 1 23 23

【问题讨论】:

  • 该程序正在按照您的指示进行操作。如果要删除整行,为什么要将其写入输出?

标签: c++ console-application


【解决方案1】:

目前您只删除每行中第一次出现的deleteline。要删除以deleteline 开头的整行,您必须替换

line.replace(line.find(deleteline), deleteline.length(), "");
temp << line << endl;

std::string id(line.begin(), line.begin() + line.find(" "));
if (id != deleteline)
    temp << line << endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多