假设我有一个简单的配置文件,我的c程序需要读取/解析.
让我们说它看起来有点像这样:
#Some comment
key1=data1
key2=data2
Run Code Online (Sandbox Code Playgroud)
有没有我可以使用的标准c lib而不是编写自己的解析器?
谢谢约翰
注意:今天我有自己的小解析器,但必须有一些标准的库可以解决这个简单的问题.
我想从文件中读取键值对,而忽略注释行.
想象一个文件,如:
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)
另外,欢迎评论我的代码风格:)