【问题标题】:C++ Setting Variable values from txt file using config classC ++使用配置类从txt文件设置变量值
【发布时间】:2015-09-09 09:44:52
【问题描述】:

我试图弄清楚如何从 txt 文件或 cfg 文件中设置变量值,现在我发现这个好用且易于使用的类。

它非常适合我的需求,但唯一的问题是它只需要字符串和双精度值,但我需要设置 int/float 值。

那么有人可以告诉我如何修改这个类,让它也接受整数和浮点数吗?

#include "Chameleon.h"

class ConfigFile {
  std::map<std::string,Chameleon> content_;

public:
  ConfigFile(std::string const& configFile);

  Chameleon const& Value(std::string const& section, std::string const& entry) const;

  Chameleon const& Value(std::string const& section, std::string const& entry, double value);
  Chameleon const& Value(std::string const& section, std::string const& entry, std::string const& value);
};

这里是 ConfigFile.cpp

std::string trim(std::string const& source, char const* delims = " \t\r\n") {
  std::string result(source);
  std::string::size_type index = result.find_last_not_of(delims);
  if(index != std::string::npos)
    result.erase(++index);

  index = result.find_first_not_of(delims);
  if(index != std::string::npos)
    result.erase(0, index);
  else
    result.erase();
  return result;
}

ConfigFile::ConfigFile(std::string const& configFile) {
  std::ifstream file(configFile.c_str());

  std::string line;
  std::string name;
  std::string value;
  std::string inSection;
  int posEqual;
  while (std::getline(file,line)) {

    if (! line.length()) continue;

    if (line[0] == '#') continue;
    if (line[0] == ';') continue;

    if (line[0] == '[') {
      inSection=trim(line.substr(1,line.find(']')-1));
      continue;
    }

    posEqual=line.find('=');
    name  = trim(line.substr(0,posEqual));
    value = trim(line.substr(posEqual+1));

    content_[inSection+'/'+name]=Chameleon(value);
  }
}

Chameleon const& ConfigFile::Value(std::string const& section, std::string const& entry) const {

  std::map<std::string,Chameleon>::const_iterator ci = content_.find(section + '/' + entry);

  if (ci == content_.end()) throw "does not exist";

  return ci->second;
}

Chameleon const& ConfigFile::Value(std::string const& section, std::string const& entry, double value) {
  try {
    return Value(section, entry);
  } catch(const char *) {
    return content_.insert(std::make_pair(section+'/'+entry, Chameleon(value))).first->second;
  }
}

Chameleon const& ConfigFile::Value(std::string const& section, std::string const& entry, std::string const& value) {
  try {
    return Value(section, entry);
  } catch(const char *) {
    return content_.insert(std::make_pair(section+'/'+entry, Chameleon(value))).first->second;
  }
}

【问题讨论】:

  • 不要发布可疑链接。而是将相关内容直接粘贴到 SO 上。

标签: c++ variables int double


【解决方案1】:

您可以执行称为typecast 的操作。将数据分配给 double 然后将其更改为 int。

【讨论】:

  • 感谢您的提示!但在我的情况下,如果有人可以帮助修改我刚刚添加到我的问题中的这个类,那么它可以采用浮点数和整数
猜你喜欢
  • 2019-09-20
  • 2012-06-15
  • 1970-01-01
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 2015-09-18
相关资源
最近更新 更多