2012-11-07 55 views
0

我有一個名爲settings.txt的文本文件。它裏面我有它說:從文本文件加載值C++

Name = Dave 

然後我打開該文件,並循環在我的腳本的線條和文字:


std::ifstream file("Settings.txt"); 
    std::string line; 

    while(std::getline(file, line)) 
{ 
    for(int i = 0; i < line.length(); i++){ 
     char ch = line[i]; 

     if(!isspace(ch)){ //skip white space 

     } 

    } 
} 

什麼,我試圖找出是將每個值分配給某種變量,這些變量將被視爲我遊戲的「全局設置」。

所以,最終的結果會是這樣的:

Username = Dave; 

但以這樣的方式,我可以在日後添加額外的設置。我不知道你會怎麼做=

+0

使用容器。 –

+0

你知道我可以在網上看到的任何示例腳本嗎? – Sir

+0

std :: map我想是你想存儲它。 –

回答

2

要添加額外的設置,你必須重新加載設置文件。通過將設置保存在std :: map中,可以添加新設置,或覆蓋現有設置。這裏是一個例子:

#include <string> 
#include <fstream> 
#include <iostream> 

#include <algorithm> 
#include <functional> 
#include <cctype> 
#include <locale> 

#include <map> 

using namespace std; 

/* -- from Evan Teran on SO: http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring -- */ 
// trim from start 
static inline std::string &ltrim(std::string &s) { 
     s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); 
     return s; 
} 

// trim from end 
static inline std::string &rtrim(std::string &s) { 
     s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); 
     return s; 
} 

// trim from both ends 
static inline std::string &trim(std::string &s) { 
     return ltrim(rtrim(s)); 
} 

int main() 
{ 
    ifstream file("settings.txt"); 
    string line; 

    std::map<string, string> config; 
    while(std::getline(file, line)) 
    { 
     int pos = line.find('='); 
     if(pos != string::npos) 
     { 
      string key = line.substr(0, pos); 
      string value = line.substr(pos + 1); 
      config[trim(key)] = trim(value); 
     } 
    } 

    for(map<string, string>::iterator it = config.begin(); it != config.end(); it++) 
    { 
     cout << it->first << " : " << it->second << endl; 
    } 
} 
+0

請問如何在後續的變量中調用數據以便在腳本中使用? – Sir

+0

@Dave不確定你的意思,但如果你的意思是訪問你的配置,或更新你的配置,你可以保持地圖(配置)作爲一個全局變量,並添加一個函數刷新該地圖,每當你加載一個新的文件。 –

+0

那麼例如可以說,文件中的某些地方它在: 'FPSMax = 60' 我想知道它是怎麼分配給一個變量在文件中,所以我可以做它像檢查if語句或東西。 ..如果這是有道理的? – Sir