问题描述
我的任务很简单 - 我只需要解析这样的文件:
My task is trivial - i just need to parse such file:
Apple = 1
Orange = 2
XYZ = 3950
但我不知道可用键的集合。我使用C#解析这个文件相对容易,让我演示源代码:
But i do not know the set of available keys. I was parsing this file relatively easy using C#, let me demonstrate source code:
public static Dictionary<string, string> ReadParametersFromFile(string path)
{
string[] linesDirty = File.ReadAllLines(path);
string[] lines = linesDirty.Where(
str => !String.IsNullOrWhiteSpace(str) && !str.StartsWith("//")).ToArray();
var dict = lines.Select(s => s.Split(new char[] { '=' }))
.ToDictionary(s => s[0].Trim(), s => s[1].Trim());
return dict;
}
现在我只需要使用c ++做同样的事情。我想使用 boost :: property_tree :: ptree
然而它似乎我只是不能迭代ini文件。很容易读取ini文件:
Now I just need to do the same thing using c++. I was thinking to use boost::property_tree::ptree
however it seems I just can not iterate over ini file. It's easy to read ini file:
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini(path, pt);
但是不可能迭代它,请参考这个问题部分中的所有条目
But it is not possible to iterate over it, refer to this question Boost program options - get all entries in section
问题是 - 在C ++上编写类似C#代码的最简单的方法是什么?
The question is - what is the easiest way to write analog of C# code above on C++ ?
推荐答案
直接回答您的问题: 当然可以迭代属性树 。其实很简单:
To answer your question directly: of course iterating a property tree is possible. In fact it's trivial:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
int main()
{
using boost::property_tree::ptree;
ptree pt;
read_ini("input.txt", pt);
for (auto& section : pt)
{
std::cout << '[' << section.first << "]\n";
for (auto& key : section.second)
std::cout << key.first << "=" << key.second.get_value<std::string>() << "\n";
}
}
b
$ b
This results in output like:
[Cat1]
name1=100 #skipped
name2=200 \#not \\skipped
name3=dhfj dhjgfd
[Cat_2]
UsagePage=9
Usage=19
Offset=0x1204
[Cat_3]
UsagePage=12
Usage=39
Offset=0x12304
我已经使用之前:
It supports comments (single line and block), quotes, escapes etc.
(作为奖励,它可选地记录所有被解析的元素的确切的源位置,这是该问题的主题)。
For your purpose, though, I think I'd recomment Boost Property Tree.
这篇关于迭代在c ++上的ini文件,可能使用boost :: property_tree :: ptree?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!