fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <vector>
  4. #include <array>
  5.  
  6.  
  7. template<class e, class t, int N>
  8. std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e(&sliteral)[N]) {
  9. std::array<e, N-1> buffer; //get buffer
  10. in >> buffer[0]; //skips whitespace
  11. if (N>2)
  12. in.read(&buffer[1], N-2); //read the rest
  13. if (strncmp(&buffer[0], sliteral, N-1)) //if it failed
  14. in.setstate(in.rdstate() | std::ios::badbit); //set the state
  15. return in;
  16. }
  17. template<class e, class t>
  18. std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e& cliteral) {
  19. e buffer; //get buffer
  20. in >> buffer; //read data
  21. if (buffer != cliteral) //if it failed
  22. in.setstate(in.rdstate() | std::ios::badbit); //set the state
  23. return in;
  24. }
  25. template<class e, class t, int N>
  26. std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, e(&carray)[N]) {
  27. return std::operator>>(in, carray);
  28. }
  29. template<class e, class t, class a>
  30. std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, a& obj) {
  31. return in >> obj; //read data
  32. }
  33.  
  34.  
  35.  
  36. struct first {
  37. std::string name;
  38. double something;
  39. };
  40. struct mega {
  41. std::vector<first> list;
  42. };
  43.  
  44. std::istream& operator>>(std::istream& file, first& obj) {
  45. std::string symbol;
  46. char equals;
  47. while(file >> symbol) {
  48. if (symbol[0] == '#') {
  49. std::getline(file, symbol);
  50. } else if (symbol == "<FIRST_END>") {
  51. break;
  52. } else if (symbol == "NAME") {
  53. if (! (file>>'='>>obj.name) )
  54. std::cerr << symbol << " incorrectly formatted";
  55. } else if (symbol == "SOMETHING") {
  56. if (! (file>>'='>>obj.something) )
  57. std::cerr << symbol << " incorrectly formatted";
  58. } else { //not a member: failure
  59. std::cerr << symbol << " is not a member of first";
  60. file.setstate(file.rdstate() | std::ios::badbit);
  61. break;
  62. }
  63. }
  64. return file;
  65. }
  66.  
  67. std::istream& operator>>(std::istream& file, mega& obj) {
  68. std::string symbol;
  69. first t;
  70. while(file >> symbol) {
  71. if (symbol[0] == '#') {
  72. std::getline(file, symbol);
  73. } else if (symbol == "<FIRST_BEGIN>") {
  74. if (file >> t)
  75. obj.list.push_back(t);
  76. } else {
  77. std::cerr << symbol << " is not a member of mega";
  78. file.setstate(file.rdstate() | std::ios::badbit);
  79. }
  80. }
  81. return file;
  82. }
  83.  
  84. int main() {
  85. mega obj;
  86. std::cin >> obj;
  87. std::cout << obj.list.size(); //1 if success
  88. }
Success #stdin #stdout 0s 3024KB
stdin
<FIRST_BEGIN>
  NAME = myname
  SOMETHING = d
<FIRST_END>

<SECOND_BEGIN>
  INT = 5
  COMPLEX = 5.0 1.0
<SECOND_END>
stdout
Standard output is empty