fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <vector>
  4. #include <list>
  5. using namespace std;
  6.  
  7. class Line
  8. {
  9. public:
  10. std::list<int> get_values() const
  11. {
  12. return { a, b, c };
  13. }
  14. private:
  15. int a, b, c;
  16.  
  17. template<class charT>
  18. friend basic_istream<charT>& operator>>(basic_istream<charT>& is,
  19. Line& line)
  20. {
  21. return is >> line.a >> line.b >> line.c;
  22. }
  23. };
  24.  
  25. class line_parser : public std::ctype<char>
  26. {
  27. public:
  28. static mask* make_table()
  29. {
  30. static std::vector<mask> v(classic_table(),
  31. classic_table() + table_size);
  32. int spaces[10] = {0x20, 0x0c, 0x0a, 0x0d, 0x09,
  33. 0x0b, '(', ',', ')', ';'};
  34. // ^^^^^^^^^^^^^^^^^^
  35.  
  36. for (int i : spaces)
  37. v[i] |= space;
  38. return &v[0];
  39. }
  40.  
  41. line_parser(int refs = 0) : ctype(make_table(), false, refs) { }
  42. };
  43.  
  44. template<class Line>
  45. class line_extractor
  46. {
  47. public:
  48. line_extractor(Line& l)
  49. : line(l)
  50. { }
  51. private:
  52. Line& line;
  53.  
  54. template<class charT>
  55. void do_input(basic_istream<charT>& is) const
  56. {
  57. locale loc = is.getloc();
  58.  
  59. is.imbue(locale(loc, new line_parser)); // imbue the new locale
  60.  
  61. is >> line;
  62. is.imbue(loc); // imbue the original locale
  63. }
  64.  
  65. template<class charT>
  66. friend basic_istream<charT>& operator>>(basic_istream<charT>& is,
  67. const line_extractor& le)
  68. {
  69. le.do_input(is);
  70. return is;
  71. }
  72. };
  73.  
  74. template<class Line>
  75. line_extractor<Line> get_line(Line& l)
  76. {
  77. return line_extractor<Line>(l);
  78. }
  79.  
  80. int main()
  81. {
  82. string line = "(1,2,3); (3,4,5);(6,7,8); (9,10,11);";
  83. stringstream ss(line);
  84. vector<Line> v;
  85.  
  86. for (Line line; ss >> get_line(line);)
  87. {
  88. v.push_back(line);
  89. }
  90.  
  91. for (auto x : v)
  92. {
  93. for (auto y : x.get_values())
  94. {
  95. std::cout << y << " ";
  96. }
  97. std::cout << std::endl;
  98. }
  99. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
1 2 3 
3 4 5 
6 7 8 
9 10 11