【问题标题】:Loading values from a text file C++从文本文件 C++ 加载值
【发布时间】:2012-10-27 02:05:05
【问题描述】:

我有一个名为settings.txt 的文本文件。在里面我说:

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;

但是通过这种方式,我可以在以后添加额外的设置。我不知道你会怎么做=/

【问题讨论】:

  • 你知道网上有什么我可以看的示例脚本吗?
  • std::map 我认为是您想要存储的内容。
  • 看看this问题

标签: c++


【解决方案1】:

要添加额外的设置,您必须重新加载设置文件。通过将设置保留在 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;
   }
}

【讨论】:

  • 请问我之后如何在变量中调用数据以在我的脚本中使用?
  • @Dave 不确定您的意思,但如果您要访问您的配置或更新您的配置,您可以将地图 (config) 保留为全局变量,并添加一个函数来刷新它每次加载新文件时映射。
  • 好吧,例如,让我们在文件中说它有的地方:FPSMax = 60 我想知道它是如何分配给文件中的变量的,所以我可以像 if 语句或其他东西一样对其进行检查...如果这有意义吗?
  • @Dave 你不能用像 C++ 这样的静态语言动态地“创建一个变量”(在 lua 中,你可以:)),所以最好的方法是从地图访问它,这里是 config["FPSMax"]
  • @Dave 它只是属性的名称,在您的示例中它是 FPSMax,second> 是某个属性的
猜你喜欢
  • 2010-10-16
  • 2010-12-08
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 2017-05-13
  • 2012-01-12
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多