I'm new to Boost Spirit. I haven't been able to find examples for some simple things. For example, suppose I have an even number of space-delimited integers. (That matches *(qi::int_ >> qi::int_)
. So far so good.) I'd like to save just the even ones to a std::vector<int>
. I've tried a variety of things like *(qi::int_ >> qi::skip[qi::int_])
https://godbolt.org/z/KPToo3xh6 but that still records every int, not just even ones.
#include <stdexcept>
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
// Example based off https://raw.githubusercontent.com/bingmann/2018-cpp-spirit-parsing/master/spirit1_simple.cpp:
// Helper to run a parser, check for errors, and capture the results.
template <typename Parser, typename Skipper, typename ... Args>
void PhraseParseOrDie(
const std::string& input, const Parser& p, const Skipper& s,
Args&& ... args)
{
std::string::const_iterator begin = input.begin(), end = input.end();
boost::spirit::qi::phrase_parse(begin, end, p, s, std::forward<Args>(args) ...);
if (begin != end) {
fmt::print("Unparseable: \"{}\"\n", std::string(begin, end));
}
}
void test(std::string input)
{
std::vector<int> out_int_list;
PhraseParseOrDie(
// input string
input,
// parser grammar
*(qi::int_ >> qi::skip[qi::int_]),
// skip parser
qi::space,
// output list
out_int_list);
fmt::print("test() parse result: {}\n", out_int_list);
}
int main(int argc, char* argv[])
{
test("12345 42 5 2");
return 0;
}
Prints
test() parse result: [12345, 42, 5, 2]