我想从文件中读取键值对,而忽略注释行.
想象一个文件,如:
key1=value1
#ignore me!
Run Code Online (Sandbox Code Playgroud)
我想出了这个,
a)看起来非常笨重
b)如果'='没有被空格包围,它就不起作用.lineStream未正确拆分,整行被读入"key".
std::ifstream infile(configFile);
std::string line;
std::map<std::string, std::string> properties;
while (getline(infile, line)) {
//todo: trim start of line
if (line.length() > 0 && line[0] != '#') {
std::istringstream lineStream(line);
std::string key, value;
char delim;
if ((lineStream >> key >> delim >> value) && (delim == '=')) {
properties[key] = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
另外,欢迎评论我的代码风格:)
我不得不制作一些在配置文件中读取并最近存储它的值的解释器,这是我做的方式,它忽略以#开头的行:
typedef std::map<std::string, std::string> ConfigInfo;
ConfigInfo configValues;
std::string line;
while (std::getline(fileStream, line))
{
std::istringstream is_line(line);
std::string key;
if (std::getline(is_line, key, '='))
{
std::string value;
if (key[0] == '#')
continue;
if (std::getline(is_line, value))
{
configValues[key] = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
fileStream是fstream一个文件.