Ticket #9152: classic_numbers.cpp

File classic_numbers.cpp, 2.7 KB (added by Matthew Markland <markland@…>, 9 years ago)

The classic numbers parser from the Spirit documentation.

Line 
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// This sample demontrates a parser for a comma separated list of numbers
12// This is discussed in the "Quick Start" chapter in the Spirit User's Guide.
13//
14// [ JDG 5/10/2002 ]
15//
16///////////////////////////////////////////////////////////////////////////////
17#include <boost/spirit/include/classic_core.hpp>
18#include <boost/spirit/include/classic_push_back_actor.hpp>
19#include <iostream>
20#include <vector>
21#include <string>
22
23///////////////////////////////////////////////////////////////////////////////
24using namespace std;
25using namespace boost::spirit::classic;
26
27///////////////////////////////////////////////////////////////////////////////
28//
29// Our comma separated list parser
30//
31///////////////////////////////////////////////////////////////////////////////
32bool
33parse_numbers(char const* str, vector<double>& v)
34{
35 return parse(str,
36
37 // Begin grammar
38 (
39 real_p[push_back_a(v)] >> *(',' >> real_p[push_back_a(v)])
40 )
41 ,
42 // End grammar
43
44 space_p).full;
45}
46
47////////////////////////////////////////////////////////////////////////////
48//
49// Main program
50//
51////////////////////////////////////////////////////////////////////////////
52int
53main()
54{
55 cout << "/////////////////////////////////////////////////////////\n\n";
56 cout << "\t\tA comma separated list parser for Spirit...\n\n";
57 cout << "/////////////////////////////////////////////////////////\n\n";
58
59 cout << "Give me a comma separated list of numbers.\n";
60 cout << "The numbers will be inserted in a vector of numbers\n";
61 cout << "Type [q or Q] to quit\n\n";
62
63 string str;
64 while (getline(cin, str))
65 {
66 if (str.empty() || str[0] == 'q' || str[0] == 'Q')
67 break;
68
69 vector<double> v;
70 if (parse_numbers(str.c_str(), v))
71 {
72 cout << "-------------------------\n";
73 cout << "Parsing succeeded\n";
74 cout << str << " Parses OK: " << endl;
75
76 for (vector<double>::size_type i = 0; i < v.size(); ++i)
77 cout << i << ": " << v[i] << endl;
78
79 cout << "-------------------------\n";
80 }
81 else
82 {
83 cout << "-------------------------\n";
84 cout << "Parsing failed\n";
85 cout << "-------------------------\n";
86 }
87 }
88
89 cout << "Bye... :-) \n\n";
90 return 0;
91}
92
93