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