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 7 #include <boost/config/warning_disable.hpp> 8 #include <boost/detail/lightweight_test.hpp> 9 10 #include <vector> 11 #include <istream> 12 #include <sstream> 13 #include <iostream> 14 15 #include <boost/spirit/include/qi.hpp> 16 #include <boost/spirit/include/support_multi_pass.hpp> 17 18 namespace qi = boost::spirit::qi; 19 namespace ascii = boost::spirit::ascii; 20 parse(std::istream & input)21std::vector<double> parse(std::istream& input) 22 { 23 // iterate over stream input 24 typedef std::istreambuf_iterator<char> base_iterator_type; 25 base_iterator_type in_begin(input); 26 27 // convert input iterator to forward iterator, usable by spirit parser 28 typedef boost::spirit::multi_pass<base_iterator_type> forward_iterator_type; 29 forward_iterator_type fwd_begin = boost::spirit::make_default_multi_pass(in_begin); 30 forward_iterator_type fwd_end; 31 32 // prepare output 33 std::vector<double> output; 34 35 // parse 36 bool r = qi::phrase_parse( 37 fwd_begin, fwd_end, // iterators over input 38 qi::double_ >> *(',' >> qi::double_) >> qi::eoi, // recognize list of doubles 39 ascii::space | '#' >> *(ascii::char_ - qi::eol) >> qi::eol, // comment skipper 40 output); // doubles are stored into this object 41 42 // error detection 43 if( !r || fwd_begin != fwd_end ) 44 throw std::runtime_error("parse error"); 45 46 // return result 47 return output; 48 } 49 main()50int main() 51 { 52 try { 53 std::stringstream str("1.0,2.0\n"); 54 std::vector<double> values = parse(str); 55 BOOST_TEST(values.size() == 2 && values[0] == 1.0 && values[1] == 2.0); 56 } 57 catch(std::exception const&) { 58 BOOST_TEST(false); 59 } 60 return boost::report_errors(); 61 } 62