0
我試圖找出如何從txt文件或cfg文件設置變量值,現在我發現這個很好用的類很容易使用。C++設置使用配置類從txt文件中設置變量值
其完美的我的需求,但唯一的問題是,它只需要字符串和雙打,但我需要設置整數/浮點值。
所以有人可以告訴我如何修改類,因此它需要整數和浮點數?
#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上粘貼相關內容。 – AndyG