【问题标题】:How can I find and replace a line of data in a text file c++如何在文本文件c ++中查找和替换一行数据
【发布时间】:2015-02-24 01:33:07
【问题描述】:

我正在尝试在 C++ 中查找和替换文本文件中的一行数据。但老实说,我不知道从哪里开始。

我正在考虑使用 replaceNumber.open("test.txt", ios::in | ios::out | ios_base::beg | ios::app);

在开头打开文件并在其上追加,但这不起作用。

有人知道完成这项任务的方法吗?

谢谢

编辑:我的文本文件只有一行,它包含一个数字,例如 504。然后用户指定一个要减去的数字,然后其结果应替换文本文件中的原始数字。

【问题讨论】:

  • 能否请您复制不适合您的代码以帮助您?谢谢
  • 如果文件不是很大,您可以使用std::getline() 读取行,添加到您想要保留的行的vector<string>,跳过您不想保留的行保持。然后将vector 写入文件。虽然通常情况下,对于这类任务,我会使用 sed 之类的东西。
  • @Adam27X 我的文本文件只有一行,它包含一个数字,例如 504。然后用户指定一个要减去的数字,然后其结果应该替换文本文件中的原始数字。
  • stackoverflow.com/q/16749090。不过,我很困惑。如果您的文本文件是包含单个数字的一​​行,则此处不涉及查找/替换。这是一个简单的读/写操作。从文件中读取值,回到开头,将新值写入文件。
  • 老实说@Ken White 我一直在寻找的是找到并替换号码。相反,我用一个简单的读/写操作替换了这段代码,它工作正常。非常感谢!

标签: c++ file text io


【解决方案1】:

是的,您可以使用 std::fstream 来执行此操作,这是我快速完成的一个快速实现。您打开文件,遍历文件中的每一行,并替换任何出现的子字符串。替换子字符串后,将该行存储到字符串向量中,关闭文件,用std::ios::trunc重新打开,然后将每一行写回空文件。

std::fstream file("test.txt", std::ios::in);

if(file.is_open()) {
    std::string replace = "bar";
    std::string replace_with = "foo";
    std::string line;
    std::vector<std::string> lines;

    while(std::getline(file, line)) {
        std::cout << line << std::endl;

        std::string::size_type pos = 0;

        while ((pos = line.find(replace, pos)) != std::string::npos){
            line.replace(pos, line.size(), replace_with);
            pos += replace_with.size();
        }

        lines.push_back(line);
    }

    file.close();
    file.open("test.txt", std::ios::out | std::ios::trunc);

    for(const auto& i : lines) {
        file << i << std::endl;
    }
}

【讨论】:

  • 这真的帮助我理解了在文件中查找和替换,因为我以前从未接触过向量。谢谢
【解决方案2】:

您可以使用std::stringstream 将从文件中读取的字符串转换为整数,并使用std::ofstreamstd::ofstream::trunc 覆盖文件。

#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <iomanip>
#include <sstream>

int main()
{

    std::ifstream ifs("test.txt");
    std::string line;
    int num, other_num;
    if(std::getline(ifs,line))
    {
            std::stringstream ss;
            ss << line;
            ss >> num;
    }
    else
    {
            std::cerr << "Error reading line from file" << std::endl;
            return 1;
    }

    std::cout << "Enter a number to subtract from " << num << std::endl;
    std::cin >> other_num;

    int diff = num-other_num;
    ifs.close();

    //std::ofstream::trunc tells the OS to overwrite the file
    std::ofstream ofs("test.txt",std::ofstream::trunc); 

    ofs << diff << std::endl;
    ofs.close();

    return 0;
}

【讨论】:

    猜你喜欢
    • 2017-06-28
    • 1970-01-01
    • 2014-03-05
    • 2020-07-29
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多