1 /*=============================================================================
2 Copyright (c) 2002-2003 Joel de Guzman
3 http://spirit.sourceforge.net/
4
5 Use, modification and distribution is subject to the Boost Software
6 License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
7 http://www.boost.org/LICENSE_1_0.txt)
8 =============================================================================*/
9 ///////////////////////////////////////////////////////////////////////////////
10 //
11 // A primitive calculator that knows how to add and subtract.
12 // [ demonstrating phoenix ]
13 //
14 // [ JDG 6/28/2002 ]
15 //
16 ///////////////////////////////////////////////////////////////////////////////
17 #include <boost/spirit/include/classic_core.hpp>
18 #include <boost/spirit/include/phoenix1_primitives.hpp>
19 #include <boost/spirit/include/phoenix1_operators.hpp>
20 #include <iostream>
21 #include <string>
22
23 ///////////////////////////////////////////////////////////////////////////////
24 using namespace std;
25 using namespace BOOST_SPIRIT_CLASSIC_NS;
26 using namespace phoenix;
27
28 ///////////////////////////////////////////////////////////////////////////////
29 //
30 // Our primitive calculator
31 //
32 ///////////////////////////////////////////////////////////////////////////////
33 template <typename IteratorT>
primitive_calc(IteratorT first,IteratorT last,double & n)34 bool primitive_calc(IteratorT first, IteratorT last, double& n)
35 {
36 return parse(first, last,
37
38 // Begin grammar
39 (
40 real_p[var(n) = arg1]
41 >> *( ('+' >> real_p[var(n) += arg1])
42 | ('-' >> real_p[var(n) -= arg1])
43 )
44 )
45 ,
46 // End grammar
47
48 space_p).full;
49 }
50
51 ////////////////////////////////////////////////////////////////////////////
52 //
53 // Main program
54 //
55 ////////////////////////////////////////////////////////////////////////////
56 int
main()57 main()
58 {
59 cout << "/////////////////////////////////////////////////////////\n\n";
60 cout << "\t\tA primitive calculator...\n\n";
61 cout << "/////////////////////////////////////////////////////////\n\n";
62
63 cout << "Give me a list of numbers to be added or subtracted.\n";
64 cout << "Example: 1 + 10 + 3 - 4 + 9\n";
65 cout << "The result is computed using Phoenix.\n";
66 cout << "Type [q or Q] to quit\n\n";
67
68 string str;
69 while (getline(cin, str))
70 {
71 if (str.empty() || str[0] == 'q' || str[0] == 'Q')
72 break;
73
74 double n;
75 if (primitive_calc(str.begin(), str.end(), n))
76 {
77 cout << "-------------------------\n";
78 cout << "Parsing succeeded\n";
79 cout << str << " Parses OK: " << endl;
80
81 cout << "result = " << n;
82 cout << "\n-------------------------\n";
83 }
84 else
85 {
86 cout << "-------------------------\n";
87 cout << "Parsing failed\n";
88 cout << "-------------------------\n";
89 }
90 }
91
92 cout << "Bye... :-) \n\n";
93 return 0;
94 }
95
96
97