2013-03-18 41 views
0

有沒有更好的方式讓我讀取文件中的值並相應地設置它們?我能以某種方式從文件中讀取一個變量名並在程序中相應地設置它嗎?例如,讀取BitDepth並將其設置爲文件中指定的值?因此,我不必檢查這一行是否是BitDepth,然後將bit_depth設置爲隨後的值?更有效的方式來讀取文件和設置變量?

std::ifstream config (exec_path + "/Data/config.ini"); 
if (!config.good()) SetStatus (EXIT_FAILURE); 
while (!config.eof()) { 
    std::string tmp; 
    std::getline (config, tmp); 
    if (tmp.find ("=") != 1) { 
     if (!tmp.substr (0, tmp.find (" ")).compare ("BitDepth")) { 
      tmp = tmp.substr (tmp.find_last_of (" ") + 1, tmp.length()); 
      bit_depth = atoi (tmp.c_str()); 
     } else if (!tmp.substr (0, tmp.find (" ")).compare ("WindowWidth")) { 
      tmp = tmp.substr (tmp.find_last_of (" ") + 1, tmp.length()); 
      screen_width = atoi (tmp.c_str()); 
     } else if (!tmp.substr (0, tmp.find (" ")).compare ("WindowHeight")) { 
      tmp = tmp.substr (tmp.find_last_of (" ") + 1, tmp.length()); 
      screen_height = atoi (tmp.c_str()); 
     } 
    } 
} 

的config.ini

[Display] 
BitDepth = 32 
WindowWidth = 853 
WindowHeight = 480 
+0

關鍵字到整數(或指向整數的指針)的映射是可能的。不一定更好,但仍然是一種可能性。儘管如此,不會爲三個項目做到這一點。 – stefan 2013-03-18 11:09:04

回答

3

你可以使用std::map使這種方法更加靈活。另外請注意,而不是檢查的config.eof()的erturn值是更好的檢查,直接的std::getline返回值:

std::map<std::string, int> myConfig; 

std::string line, key, delim; 
while (std::getline(config, line)) 
{ 
    // skip empty lines: 
    if (line.empty()) continue; 

    // construct stream and extract tokens from it: 
    std::string key, delim; 
    int val; 
    if (!(std::istringstream(line) >> key >> delim >> val) || delim != "=") 
     break; // TODO: reading from the config failed 

    // store the new key-value config record: 
    myConfig[key] = val; 
} 

這取決於你如何處理這種情況時的配置線之一的解析失敗:)

+3

兩件事:(1)你爲什麼要在四條語句中而不是一條/兩條('if(not(iss >> key >> delim >> val)或delim!=「=」)'...) (2)我不認爲像你的代碼現在那樣默默吞下錯誤是件好事。 – 2013-03-18 11:18:41

+0

@KonradRudolph:好的,謝謝。我編輯了我的答案。 – LihO 2013-03-18 12:05:09

相關問題