How to find and replace a data string in a C ++ text file

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

I was thinking about using replaceNumber.open ("test.txt", ios :: in | ios :: out | ios_base :: beg | ios :: app);

To open the file at the beginning and add it, but this will not work.

Does anyone know a way to achieve this?

thank

Edit: My text file is only one line and contains a number, for example, 504. Then the user specifies the number to subtract, then the result of this should replace the original number in the text file.

+4
source share
2 answers

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

std::stringstream , , std::ofstream std::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;
}
+1

Source: https://habr.com/ru/post/1569083/


All Articles