gpt4 book ai didi

c++ - spirit 上如何解析字符串并将其用作返回值

转载 作者:行者123 更新时间:2023-12-01 14:52:19 25 4
gpt4 key购买 nike

我需要解析一个键值对,其中键本身是示例中的固定字符串lke'cmd'。不幸的是qi::lit没有综合属性,并且qi::char_没有解析固定的字符串。
以下代码无法编译。执行后,我需要那个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不公开属性。 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";
}
}
}

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

关于c++ - spirit 上如何解析字符串并将其用作返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62386098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com