2012-11-07 49 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