c-使用Boost Spirit将默认值分配给变量
作者:互联网
假设我要解析以下字符串:
“ 1.2、2.0、3.9”
当我为其应用以下解析器时:
struct DataStruct
{
double n1, n2, n3;
};
BOOST_FUSION_ADAPT_STRUCT(DataStruct, (double, n1)(double, n2)(double, n3))
qi::rule<std::string::iterator, DataStruct()> data_ =
qi::double_ >> ','
>> qi::double_ >> ','
>> qi::double_;
auto str = "1.2, 2.0, 3.9";
auto it - str.begin();
if (qi::parse(it, str.end(), data_, res))
{
std::cout << "parse completed" << std::endl;
}
一切正常,但是当我假设我的字符串不是某个双精度数时,我可以得到“ null”(即“ 1.2,null,3.9”),我想将0值分配给DataStruct中适当的double值.有什么办法吗?
解决方法:
通常的技巧是使用qi :: attr的替代方法:
rule_def = parser_expression | qi::attr(default_value);
就您而言,也许:
reader_ = qi::double_ | qi::lit("null") >> qi::attr(0);
演示
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
struct DataStruct { double n1, n2, n3; };
BOOST_FUSION_ADAPT_STRUCT(DataStruct, n1, n2, n3)
namespace qi = boost::spirit::qi;
int main() {
using Iterator = typename std::string::const_iterator;
qi::rule<Iterator, double()> reader_ = qi::double_ | qi::lit("null") >> qi::attr(0);
qi::rule<Iterator, DataStruct()> data_ = reader_ >> ',' >> reader_ >> ',' >> reader_;
DataStruct res;
auto const str = std::string("1.2,null,3.9");
Iterator start = str.begin(), end = str.end();
if (qi::parse(start, end, data_ >> qi::eoi, res)) {
std::cout << "parsed: " << boost::fusion::as_vector(res) << "\n";
}
else {
std::cout << "parse failed\n";
}
}
打印
parsed: (1.2 0 3.9)
注意检查更改(不要使用名称空间,请检查eoi).
标签:c,boost,boost-spirit 来源: https://codeday.me/bug/20191011/1893377.html