2013-06-24 43 views
0

嗨,我使用此代碼找到包含seta r_fullscreen "0"的行,如果此行的值爲0返回MessageBox,但我的問題是如果seta r_fullscreen的值是「0」可以在這一行中將此值替換爲「1」?替換C++中的文本行中的某些值

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

     ... 
+0

你試過嗎? 'cfgLine.at(19)=「1'' – ruben2020

+1

要更換哪裏 '1'?在字符串中還是在.cfg文件中? – Marius

+0

在.cfg文件 – user2468671

回答

1

您可以使用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 (/*...*/); 
+0

這一切的答案是完美的,但我不知道爲什麼在我的CFG文件中該值也不變爲「1」?! :| – user2468671

+0

您是否將更改保存到配置文件? –

+0

yes pleas在pastebin中查看我的完整源代碼,或許對其有幫助的感謝。 [鏈接] http://pastebin.com/fqGWar0n – user2468671