1 /*=============================================================================
2 Copyright (c) 2002-2015 Joel de Guzman
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 ///////////////////////////////////////////////////////////////////////////////
8 //
9 // This sample demontrates a parser for a comma separated list of numbers.
10 // No semantic actions.
11 //
12 // [ JDG May 10, 2002 ] spirit1
13 // [ JDG March 24, 2007 ] spirit2
14 // [ JDG May 12, 2015 ] spirit X3
15 //
16 ///////////////////////////////////////////////////////////////////////////////
17
18 #include <boost/config/warning_disable.hpp>
19 #include <boost/spirit/home/x3.hpp>
20
21 #include <iostream>
22 #include <string>
23 #include <vector>
24
25 namespace client
26 {
27 namespace x3 = boost::spirit::x3;
28 namespace ascii = boost::spirit::x3::ascii;
29
30 ///////////////////////////////////////////////////////////////////////////
31 // Our number list parser
32 ///////////////////////////////////////////////////////////////////////////
33 template <typename Iterator>
parse_numbers(Iterator first,Iterator last)34 bool parse_numbers(Iterator first, Iterator last)
35 {
36 using x3::double_;
37 using x3::phrase_parse;
38 using ascii::space;
39
40 bool r = phrase_parse(
41 first, // Start Iterator
42 last, // End Iterator
43 double_ >> *(',' >> double_), // The Parser
44 space // The Skip-Parser
45 );
46 if (first != last) // fail if we did not get a full match
47 return false;
48 return r;
49 }
50 }
51
52 ////////////////////////////////////////////////////////////////////////////
53 // Main program
54 ////////////////////////////////////////////////////////////////////////////
55 int
main()56 main()
57 {
58 std::cout << "/////////////////////////////////////////////////////////\n\n";
59 std::cout << "\t\tA comma separated list parser for Spirit...\n\n";
60 std::cout << "/////////////////////////////////////////////////////////\n\n";
61
62 std::cout << "Give me a comma separated list of numbers.\n";
63 std::cout << "Type [q or Q] to quit\n\n";
64
65 std::string str;
66 while (getline(std::cin, str))
67 {
68 if (str.empty() || str[0] == 'q' || str[0] == 'Q')
69 break;
70
71 if (client::parse_numbers(str.begin(), str.end()))
72 {
73 std::cout << "-------------------------\n";
74 std::cout << "Parsing succeeded\n";
75 std::cout << str << " Parses OK: " << std::endl;
76 }
77 else
78 {
79 std::cout << "-------------------------\n";
80 std::cout << "Parsing failed\n";
81 std::cout << "-------------------------\n";
82 }
83 }
84
85 std::cout << "Bye... :-) \n\n";
86 return 0;
87 }
88