在c++中替换文本行中的某个值

replace some value in text line in c++

本文关键字:文本 c++ 替换      更新时间:2023-10-16

大家好,我用这段代码来查找包含seta r_fullscreen "0"的行,如果这一行的值是0,则返回MessageBox,但我的问题是,如果seta r_fullscreen的值是"0",那么我如何将这一行中的值替换为"1"?

ifstream cfgm2("players\config_m2.cfg",ios::in);
string cfgLine; 
    Process32First(proc_Snap , &pe32);
    do{     
        while (getline(cfgm2,cfgLine)) {
        if (string::npos != cfgLine.find("seta r_fullscreen")){
        if (cfgLine.at(19) == '0'){
        MessageBox(NULL,"run in full Screen mod.","ERROR", MB_OK | MB_ICONERROR);
        ...

您可以使用std::string::find()std::string::replace()来执行此操作。找到包含配置说明符seta r_fullscreen的行后,可以执行以下操作。

std::string::size_type pos = cfgLine.find(""0"");
if(pos != std::string::npos)
{
    cfgLine.replace(pos, 3, ""1"");
}

您不应该假设配置值"0"处于特定偏移,因为r_fullscreen"0"之间可能存在额外的空格。

在看到您的附加注释后,您需要在进行更改后更新配置文件。对字符串所做的更改仅适用于内存中的副本,不会自动保存到文件中。您需要在加载和更改每一行后保存它,然后将更新保存到文件中。您还应该将更新配置文件的过程移到do/while循环之外。如果你不这样做,你会阅读/更新你检查的每个过程的文件。

下面的例子应该让你开始。

#include <fstream>
#include <string>
#include <vector>

std::ifstream cfgm2("players\config_m2.cfg", std::ios::in);
if(cfgm2.is_open())
{
    std::string cfgLine; 
    bool changed = false;
    std::vector<std::string> cfgContents;
    while (std::getline(cfgm2,cfgLine))
    {
        // Check if this is a line that can be changed
        if (std::string::npos != cfgLine.find("seta r_fullscreen"))
        {
            // Find the value we want to change
            std::string::size_type pos = cfgLine.find(""0"");
            if(pos != std::string::npos)
            {
                // We found it, not let's change it and set a flag indicating the
                // configuration needs to be saved back out.
                cfgLine.replace(pos, 3, ""1"");
                changed = true;
            }
        }
        // Save the line for later.
        cfgContents.push_back(cfgLine);
    }
    cfgm2.close();
    if(changed == true)
    {
        // In the real world this would be saved to a temporary and the
        // original replaced once saving has successfully completed. That
        // step is omitted for simplicity of example.
        std::ofstream outCfg("players\config_m2.cfg", std::ios::out);
        if(outCfg.is_open())
        {
            // iterate through every line we have saved in the vector and save it
            for(auto it = cfgContents.begin();
                it != cfgContents.end();
                ++it)
            {
                outCfg << *it << std::endl;
            }
        }
    }
}
// Rest of your code
Process32First(proc_Snap , &pe32);
do {
    // some loop doing something I don't even want to know about
} while ( /*...*/ );