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

后端 未结 2 834
死守一世寂寞
死守一世寂寞 2021-01-13 18:23

I am trying to find and replace a line of data in a text file in c++. But I honestly have no idea where to start.

I was thinking of using replaceNumber.open(\"

相关标签:
2条回答
  • 2021-01-13 18:39

    Yes, you can do this using std::fstream, here's a quick implementation i whipped up real quick. You open the file, iterate over each line in the file, and replace any occurrences of your substring. After replacing the substring, store the line into a vector of strings, close the file, reopen it with std::ios::trunc, and write each line back to the empty file.

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-13 18:51

    You can use std::stringstream to convert the string read from the file to an integer and use std::ofstream with std::ofstream::trunc to overwrite the file.

    #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;
    }
    
    0 讨论(0)
提交回复
热议问题