boost spirit qi - 将字符串解析为布尔值

时间:2017-08-23 09:46:24

标签: c++ parsing boost-spirit-qi

我需要将字符串解析为布尔值;特别是

  • 如果字符串是ack我希望解析器使用true设置布尔变量;
  • 如果字符串是noack我希望解析器使用false设置布尔变量;

请注意,我不想使用函数qi::parse的返回值;我希望qi::parse函数设置一个作为参数给出的布尔变量。类似于以下(不编译)代码:

#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>

using namespace boost::spirit;

int main() {
    bool b;
    std::string s("ack");
    auto it = s.begin();
    if (qi::parse(it, s.end(), < need a rule here... >, b))
        std::cout << "Value: " << std::boolalpha << b << std::endl;
    return 0;
}

提前多多感谢。

1 个答案:

答案 0 :(得分:0)

我想到的最简单的方法是"noack" >> qi::attr(false)及其补充。添加eoi以确保解析完整输入:

<强> Live On Coliru

#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>

namespace qi = boost::spirit::qi;

int main() {
    for (std::string const s : {"ack","noack","oops","ack 2",""}) {
        bool b;
        if (qi::parse(s.begin(), s.end(), ("ack" >> qi::attr(true) | "noack" >> qi::attr(false)) >> qi::eoi, b))
            std::cout << "'" << s << "' -> " << std::boolalpha << b << std::endl;
        else
            std::cout << "'" << s << "' -> FAIL\n";
    }
}

打印

'ack' -> true
'noack' -> false
'oops' -> FAIL
'ack 2' -> FAIL
'' -> FAIL

奖金:

使用symbol更优雅:

<强> Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>

namespace qi = boost::spirit::qi;

struct acknoack_type : qi::symbols<char, bool> {
    acknoack_type() { this->add("ack", true)("noack", false); }
} static const acknoack;

int main() {
    for (std::string const s : {"ack","noack","oops","ack 2",""}) {
        bool b;
        if (qi::parse(s.begin(), s.end(), acknoack >> qi::eoi, b))
            std::cout << "'" << s << "' -> " << std::boolalpha << b << std::endl;
        else
            std::cout << "'" << s << "' -> FAIL\n";
    }
}