regression_multi_pass_parse.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (c) 2010 Peter Schueller
  2. // Copyright (c) 2001-2010 Hartmut Kaiser
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #include <boost/config/warning_disable.hpp>
  7. #include <boost/detail/lightweight_test.hpp>
  8. #include <vector>
  9. #include <istream>
  10. #include <sstream>
  11. #include <iostream>
  12. #include <boost/spirit/include/qi.hpp>
  13. #include <boost/spirit/include/support_multi_pass.hpp>
  14. namespace qi = boost::spirit::qi;
  15. namespace ascii = boost::spirit::ascii;
  16. std::vector<double> parse(std::istream& input)
  17. {
  18. // iterate over stream input
  19. typedef std::istreambuf_iterator<char> base_iterator_type;
  20. base_iterator_type in_begin(input);
  21. // convert input iterator to forward iterator, usable by spirit parser
  22. typedef boost::spirit::multi_pass<base_iterator_type> forward_iterator_type;
  23. forward_iterator_type fwd_begin = boost::spirit::make_default_multi_pass(in_begin);
  24. forward_iterator_type fwd_end;
  25. // prepare output
  26. std::vector<double> output;
  27. // parse
  28. bool r = qi::phrase_parse(
  29. fwd_begin, fwd_end, // iterators over input
  30. qi::double_ >> *(',' >> qi::double_) >> qi::eoi, // recognize list of doubles
  31. ascii::space | '#' >> *(ascii::char_ - qi::eol) >> qi::eol, // comment skipper
  32. output); // doubles are stored into this object
  33. // error detection
  34. if( !r || fwd_begin != fwd_end )
  35. throw std::runtime_error("parse error");
  36. // return result
  37. return output;
  38. }
  39. int main()
  40. {
  41. try {
  42. std::stringstream str("1.0,2.0\n");
  43. std::vector<double> values = parse(str);
  44. BOOST_TEST(values.size() == 2 && values[0] == 1.0 && values[1] == 2.0);
  45. }
  46. catch(std::exception const&) {
  47. BOOST_TEST(false);
  48. }
  49. return boost::report_errors();
  50. }