fork(1) download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4. #include <vector>
  5. //#include <fstream>
  6.  
  7. using namespace std;
  8.  
  9. struct tagattribute {
  10. string name;
  11. string value;
  12. };
  13.  
  14. istream& operator>>(istream &in, tagattribute &attr)
  15. {
  16. getline(in, attr.name, '=');
  17. in.ignore();
  18. getline(in, attr.value, '"');
  19. return in;
  20. }
  21.  
  22. struct tagline {
  23. string tag;
  24. vector<tagattribute> attributes;
  25. };
  26.  
  27. istream& operator>>(istream &in, tagline &t)
  28. {
  29. tagattribute attr;
  30.  
  31. in >> std::ws;
  32.  
  33. char ch = in.get();
  34. if (ch != '<')
  35. {
  36. in.setstate(ios_base::failbit);
  37. return in;
  38. }
  39.  
  40. if (!(in >> t.tag))
  41. return in;
  42.  
  43. do
  44. {
  45. in >> std::ws;
  46.  
  47. ch = in.peek();
  48. if (ch == '>')
  49. {
  50. in.ignore();
  51. break;
  52. }
  53.  
  54. if (!(in >> attr))
  55. break;
  56.  
  57. t.attributes.push_back(attr);
  58. }
  59. while (true);
  60.  
  61. return in;
  62. }
  63.  
  64. int main() {
  65. vector<tagline> information;
  66. string line;
  67.  
  68. //ifstream readFile("file.txt");
  69. istream &readFile = cin;
  70.  
  71. while (getline(readFile, line)) {
  72. istringstream in(line);
  73. tagline t;
  74.  
  75. if (in >> t)
  76. information.push_back(t);
  77. }
  78.  
  79. vector<tagline>::iterator it = information.begin();
  80. for(; it != information.end(); ++it) {
  81. cout << "Tag: " << it->tag << "\n";
  82.  
  83. vector<tagattribute>::iterator it2 = it->attributes.begin();
  84. for(; it2 != it->attributes.end(); ++it2) {
  85. cout << "name: " << it2->name << "\n"
  86. << "value: " << it2->value << "\n";
  87. }
  88.  
  89. cout << "\n";
  90. }
  91.  
  92. return 0;
  93. }
Success #stdin #stdout 0s 4356KB
stdin
<tag1 attr1="value1" attr2="value2" >
<tag2 attr1="value1" attr2="value2" >
stdout
Tag: tag1
name: attr1
value: value1
name: attr2
value: value2

Tag: tag2
name: attr1
value: value1
name: attr2
value: value2