简体   繁体   English

如何在精神上解析字符串并将其用作返回值

[英]How to parse a string in spirit and use it as return value

I need to parse a key value pair, where key itself is a fixed string lke 'cmd' in the example.我需要解析一个键值对,其中键本身是一个固定字符串 lke 'cmd' 在示例中。 Unfortunately qi::lit has no synthesized attribute and qi::char_ parses no fixed string.不幸的是 qi::lit 没有综合属性并且 qi::char_ 解析没有固定的字符串。 Following code does not compile.以下代码无法编译。 I would need that result.name == cmd after execution.执行后我需要那个 result.name == cmd 。

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <iomanip>
#include <string>

namespace qi = boost::spirit::qi;
namespace px = boost::phoenix;

struct CommandRuleType
{
  std::string name;
  int arg;
};

BOOST_FUSION_ADAPT_STRUCT(CommandRuleType, name, arg)

int main() {
    qi::rule<std::string::const_iterator, CommandRuleType(), qi::space_type> rule = qi::lit("cmd") >> "=" >> qi::int_;

    for (std::string const s : {"cmd = 1" }) {
        std::cout << std::quoted(s) << " -> ";
        CommandRuleType result;
        if (qi::phrase_parse(s.begin(), s.end(), rule, qi::space, result)) {
            std::cout << "result: " << result.name << "=" << result.arg << "\n";
        } else {
            std::cout << "parse failed\n";
        }
    }
}

qi::lit does not expose an attribute. qi::lit不公开属性。 qi::string does: qi::string会:

    rule = qi::string("cmd") >> "=" >> qi::int_;

Live On Coliru住在科利鲁

#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iomanip>
#include <string>

namespace qi = boost::spirit::qi;
namespace px = boost::phoenix;

struct CommandRuleType {
    std::string name;
    int arg;
};

BOOST_FUSION_ADAPT_STRUCT(CommandRuleType, name, arg)

int main() {
    qi::rule<std::string::const_iterator, CommandRuleType(), qi::space_type>
        rule = qi::string("cmd") >> "=" >> qi::int_;

    for (std::string const s : { "cmd = 1" }) {
        std::cout << std::quoted(s) << " -> ";
        CommandRuleType result;
        if (qi::phrase_parse(s.begin(), s.end(), rule, qi::space, result)) {
            std::cout << "result: " << result.name << "=" << result.arg << "\n";
        } else {
            std::cout << "parse failed\n";
        }
    }
}

Prints印刷

"cmd = 1" -> result: cmd=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM