在 boost::spirit 中,我添加了基于 example roman 的错误处理代码。
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
template <typename Iterator>
struct roman : qi::grammar<Iterator>
{
roman() : roman::base_type(start)
{
using qi::eps;
using qi::lit;
using qi::lexeme;
using qi::_val;
using qi::_1;
using ascii::char_;
// for on_error
using qi::on_error;
using qi::fail;
using phoenix::construct;
using phoenix::val;
start = +(lit('M') ) >> "</>";
on_error<fail>
(
start
, std::cout
<< val("Error! Expecting ")
// << _4 // what failed?
<< val(" here: \"")
// << construct<std::string>(_3, _2) // iterators to error-pos, end
<< val("\"")
<< std::endl
);
}
qi::rule<Iterator> start;
};
int
main()
{
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "\t\tRoman Numerals Parser\n\n";
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Type a Roman Numeral ...or [q or Q] to quit\n\n";
typedef std::string::const_iterator iterator_type;
typedef roman<iterator_type> roman;
roman roman_parser; // Our grammar
std::string str;
unsigned result;
while (std::getline(std::cin, str))
{
if (str.empty() || str[0] == 'q' || str[0] == 'Q')
break;
std::string::const_iterator iter = str.begin();
std::string::const_iterator end = str.end();
//[tutorial_roman_grammar_parse
bool r = parse(iter, end, roman_parser, result);
if (r && iter == end)
{
std::cout << "-------------------------\n";
std::cout << "Parsing succeeded\n";
std::cout << "result = " << result << std::endl;
std::cout << "-------------------------\n";
}
else
{
std::string rest(iter, end);
std::cout << "-------------------------\n";
std::cout << "Parsing failed\n";
std::cout << "stopped at: \": " << rest << "\"\n";
std::cout << "-------------------------\n";
}
//]
}
std::cout << "Bye... :-) \n\n";
return 0;
}
我的问题是:
- “on_error”没有被触发,为什么?
- 我注释了“<< _4”,如果我想打印出失败的部分,该怎么做?