/////////////////////////////////////////////////////////////////////////////// // // Demonstrates use of boost::bind and spirit // // [ JDG 10/16/2002 ] // /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include /////////////////////////////////////////////////////////////////////////////// using namespace std; using namespace spirit; using namespace boost; /////////////////////////////////////////////////////////////////////////////// // // Our comma separated list parser // /////////////////////////////////////////////////////////////////////////////// class pair_list_parser { public: typedef pair_list_parser self_t; typedef std::map map_t; bool parse(char const* str) { int key; return spirit::parse(str, // Begin grammar ( '[' >> ( ( '(' >> int_p [assign(key)] >> ',' >> int_p [bind(&self_t::add, this, ref(key), _1)] >> ')' ) % ',' ) >> ']' ) , // End grammar space_p).full; } void add(int key, int val) { int_map[key] = val; } void print() const { for (map_t::const_iterator i = int_map.begin(); i != int_map.end(); ++i) cout << i->first << ", " << i->second << endl; } map_t int_map; }; //////////////////////////////////////////////////////////////////////////// // // Main program // //////////////////////////////////////////////////////////////////////////// int main() { cout << "/////////////////////////////////////////////////////////\n\n"; cout << "\tA comma separated int pair list parser for Spirit...\n"; cout << "\tDemonstrates use of boost::bind and spirit\n"; cout << "/////////////////////////////////////////////////////////\n\n"; cout << "Give me a comma separated paired list of numbers of the form.\n"; cout << "[(k1,n1),(k2,n2)(k3,n3)...].\n"; cout << "The number pairs will be added in a map\n"; cout << "Type [q or Q] to quit\n\n"; string str; while (getline(cin, str)) { if (str[0] == 'q' || str[0] == 'Q') break; pair_list_parser lp; if (lp.parse(str.c_str())) { cout << "-------------------------\n"; cout << "Parsing succeeded\n"; lp.print(); cout << "-------------------------\n"; } else { cout << "-------------------------\n"; cout << "Parsing failed\n"; cout << "-------------------------\n"; } } cout << "Bye... :-) \n\n"; return 0; }