| 1 | // Copyright (c) 2001-2010 Hartmut Kaiser |
| 2 | // |
| 3 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 4 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 5 | |
| 6 | // The purpose of this example is to show how any character sequence can be |
| 7 | // printed while being properly quoted. |
| 8 | |
| 9 | #include <boost/spirit/include/karma.hpp> |
| 10 | |
| 11 | namespace client |
| 12 | { |
| 13 | namespace karma = boost::spirit::karma; |
| 14 | |
| 15 | template <typename OutputIterator> |
| 16 | struct escaped_string |
| 17 | : karma::grammar<OutputIterator, std::string(char const*)> |
| 18 | { |
| 19 | escaped_string() |
| 20 | : escaped_string::base_type(esc_str) |
| 21 | { |
| 22 | esc_char.add('\a', "\\a" )('\b', "\\b" )('\f', "\\f" )('\n', "\\n" ) |
| 23 | ('\r', "\\r" )('\t', "\\t" )('\v', "\\v" )('\\', "\\\\" ) |
| 24 | ('\'', "\\\'" )('\"', "\\\"" ) |
| 25 | ; |
| 26 | |
| 27 | esc_str = karma::lit(karma::_r1) |
| 28 | << *(esc_char | karma::print | "\\x" << karma::hex) |
| 29 | << karma::lit(karma::_r1) |
| 30 | ; |
| 31 | } |
| 32 | |
| 33 | karma::rule<OutputIterator, std::string(char const*)> esc_str; |
| 34 | karma::symbols<char, char const*> esc_char; |
| 35 | }; |
| 36 | } |
| 37 | |
| 38 | /////////////////////////////////////////////////////////////////////////////// |
| 39 | int main() |
| 40 | { |
| 41 | namespace karma = boost::spirit::karma; |
| 42 | |
| 43 | typedef std::back_insert_iterator<std::string> sink_type; |
| 44 | |
| 45 | std::string generated; |
| 46 | sink_type sink(generated); |
| 47 | |
| 48 | std::string str("string to escape: \n\r\t\"'\x19" ); |
| 49 | char const* quote = "'''" ; |
| 50 | |
| 51 | client::escaped_string<sink_type> g; |
| 52 | if (!karma::generate(sink_&: sink, expr: g(quote), attr: str)) |
| 53 | { |
| 54 | std::cout << "-------------------------\n" ; |
| 55 | std::cout << "Generating failed\n" ; |
| 56 | std::cout << "-------------------------\n" ; |
| 57 | } |
| 58 | else |
| 59 | { |
| 60 | std::cout << "-------------------------\n" ; |
| 61 | std::cout << "Generated: " << generated << "\n" ; |
| 62 | std::cout << "-------------------------\n" ; |
| 63 | } |
| 64 | return 0; |
| 65 | } |
| 66 | |