gpt4 book ai didi

c++ - boost spirit 和凤凰解析为 std::string

转载 作者:搜寻专家 更新时间:2023-10-31 02:15:26 24 4
gpt4 key购买 nike

如何解析成带有 boost spirit 和 phoenix 的 std::string?

例如,下面我成功地将 1234 解析为一个 int,但是当我尝试解析为一个字符串时,解析失败了。如果我将 qi::alnum 替换为 +qi::alnum 则解析成功但字符串编号具有不需要的值“4”。好像 qi::alnum 只匹配一个字符;如何解析多字符字母数字字符串?

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

#include <iostream>
#include <string>

int main() {

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

std::string s("--1234--");

{
int number = 0;
bool success = qi::parse(s.begin(), s.end(),
qi::lit("--") >> qi::int_[ phoenix::ref(number) = qi::_1 ] >> qi::lit("--")
);
std::cout << success << " qi::int_ parses: " << number << std::endl;
}

{
std::string number;
bool success = qi::parse(s.begin(), s.end(),
qi::lit("--") >> qi::alnum[ phoenix::ref(number) = qi::_1 ] >> qi::lit("--")
);
std::cout << success << " qi::alpha parses: " << number << std::endl;
}

return 0;
}

最佳答案

使用qi::as_string ,例如

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

#include <iostream>
#include <string>

int main() {

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

std::string s("--1234--");

std::string number;
bool success = qi::parse( s.begin(), s.end(),
qi::lit("--")
>> qi::as_string [ +qi::alnum ] [ phoenix::ref(number) = qi::_1 ]
>> qi::lit("--"));
std::cout << success << " qi::as_string parses: " << number << std::endl;

return 0;
}

关于c++ - boost spirit 和凤凰解析为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494058/

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