在 C++ 中搜索和编辑文件

use*_*376 2 c++

大家好,我正在为我的 C++ 主题制作一个数据库项目,我想寻求有关如何在 C++ 中编辑或替换文件的帮助。我找不到可以编辑或替换我创建的文件中的项目的最简单的程序。

文本.txt:

name: John Rodriguez

age:12

name: Edward Bantatua

age:15

name: Hemerson Fortunato

age:18
Run Code Online (Sandbox Code Playgroud)

在示例中,我想编辑 Hemerson Fortunato 并更改他的姓名和年龄。任何人都可以帮助我为其制作一个程序吗?,非常感谢任何帮助我的人。对不起,我的英语不好。

cpp*_*cpp 6

将文件的内容读入字符串并使用replace(). 然后将字符串写回到文件中。像这样的东西:

#include <string>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    ostringstream text;
    ifstream in_file("Text.txt");

    text << in_file.rdbuf();
    string str = text.str();
    string str_search = "Fortunato";
    string str_replace = "NotFortunato";
    size_t pos = str.find(str_search);
    str.replace(pos, string(str_search).length(), str_replace);
    in_file.close();

    ofstream out_file("Text.txt");
    out_file << str;     
}
Run Code Online (Sandbox Code Playgroud)

使用regex_replace(C++11) 或boost:regex进行更高级的查找和替换操作。