如何在文本文件 c++ 中查找和替换一行数据

How can I find and replace a line of data in a text file c++

本文关键字:替换 数据 一行 查找 文本 文件 c++      更新时间:2023-10-16

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

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

开头打开文件并附加在它上面,但这不起作用。

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

谢谢

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

是的,你可以使用 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;
    }
}
可以使用

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;
}