fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <boost/spirit/include/qi.hpp>
  4.  
  5. namespace qi = boost::spirit::qi;
  6. namespace ascii = boost::spirit::ascii;
  7.  
  8.  
  9. template <typename T>
  10. struct real_with_separated_sign_policies : boost::spirit::qi::real_policies<T>
  11. {
  12. // allow skipping chars between a possible sign and a folling real number
  13. template <typename Iterator>
  14. static bool parse_sign(Iterator& first, Iterator const& last)
  15. {
  16. bool ret = qi::extract_sign(first, last);
  17. if (ret)
  18. qi::parse(first, last, *qi::lit(' '));
  19. return ret;
  20. }
  21. };
  22.  
  23.  
  24. template <typename Iterator, typename Skipper>
  25. struct RealWithSeparatedSignParser
  26. : qi::grammar<Iterator, double(), Skipper>
  27. {
  28. boost::spirit::qi::real_parser<double, real_with_separated_sign_policies<double> > RealWithSeparatedSignValue;
  29.  
  30. RealWithSeparatedSignParser() : RealWithSeparatedSignParser::base_type(start)
  31. {
  32. start %= RealWithSeparatedSignValue;
  33. }
  34.  
  35. qi::rule<Iterator, double(), Skipper> start;
  36. };
  37.  
  38. int main() {
  39. std::string str = " - 1.234 ";
  40. std::string::const_iterator it = str.begin();
  41. std::string::const_iterator endIt = str.end();
  42. RealWithSeparatedSignParser<std::string::const_iterator, ascii::space_type> grammar;
  43. double realWithSeparatedSign;
  44. bool ret = phrase_parse(it, endIt, grammar, ascii::space, realWithSeparatedSign);
  45. std::cout << ret << " " << realWithSeparatedSign;
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
1 -1.234