fork(5) download
  1. #include <string>
  2. #include <boost/spirit/include/qi.hpp>
  3. #include <boost/fusion/include/adapt_struct.hpp>
  4.  
  5. struct Date {
  6. int year, month, day;
  7. };
  8. struct Time {
  9. int hour, minute, second;
  10. };
  11.  
  12. BOOST_FUSION_ADAPT_STRUCT(
  13. Date,
  14. (int, year)
  15. (int, month)
  16. (int, day)
  17. )
  18.  
  19. BOOST_FUSION_ADAPT_STRUCT(
  20. Time,
  21. (int, hour)
  22. (int, minute)
  23. (int, second)
  24. )
  25.  
  26. namespace qi = boost::spirit::qi;
  27. namespace ascii = boost::spirit::ascii;
  28. typedef std::string::const_iterator Iterator;
  29.  
  30. class DateParser:
  31. public qi::grammar < Iterator, Date() > {
  32. qi::rule < Iterator, Date() > main;
  33. public:
  34. DateParser(): base_type(main) {
  35. main %= qi::int_ >> '-' >> // Year
  36. qi::int_ >> '-' >> // Month
  37. qi::int_; // Day
  38. }
  39. };
  40.  
  41. class TimeParser:
  42. public qi::grammar < Iterator, Time() > {
  43. qi::rule < Iterator, Time() > main;
  44. public:
  45. TimeParser(): base_type(main) {
  46. main %= qi::int_ >> ':' >> // Hour
  47. qi::int_ >> ':' >> // Minute
  48. qi::int_; // Second
  49. }
  50. };
  51.  
  52. class DateTimeParser:
  53. public qi::grammar < Iterator, boost::variant<Date, Time>() > {
  54. qi::rule < Iterator, boost::variant<Date, Time>()> main;
  55. public:
  56. DateTimeParser(): base_type(main) {
  57. main %= date_parser | time_parser;
  58. }
  59. DateParser date_parser;
  60. TimeParser time_parser;
  61. };
  62.  
  63. #include<iostream>
  64. #include<cstdio>
  65.  
  66. struct Printer : public boost::static_visitor<> {
  67. void operator()(Date a) const {
  68. printf("Year: %d, Month: %d, Day: %d\n", a.year, a.month, a.day);
  69. }
  70. void operator()(Time a) const {
  71. printf("Hour: %d, Minute: %d, Second: %d\n", a.hour, a.minute, a.second);
  72. }
  73. };
  74.  
  75. int main() {
  76. std::string s;
  77. std::getline(std::cin, s);
  78. Iterator beg = s.begin(), end = s.end();
  79. boost::variant<Date, Time> ret;
  80. phrase_parse(beg, end, DateTimeParser(), ascii::space, ret);
  81. if (beg != end)
  82. puts("Parse failed.");
  83. else
  84. boost::apply_visitor(Printer(), ret);
  85. }
  86.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty