fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4.  
  5. int main()
  6. {
  7. std::string xml("a < > & ' \" string");
  8. std::cout << xml << "\n";
  9.  
  10. // Characters to be transformed.
  11. //
  12. std::map<char, std::string> transformations;
  13. transformations['&'] = std::string("&amp;");
  14. transformations['\''] = std::string("&apos;");
  15. transformations['"'] = std::string("&quot;");
  16. transformations['>'] = std::string("&gt;");
  17. transformations['<'] = std::string("&lt;");
  18.  
  19. // Build list of characters to be searched for.
  20. //
  21. std::string reserved_chars;
  22. for (auto ti = transformations.begin(); ti != transformations.end(); ti++)
  23. {
  24. reserved_chars += ti->first;
  25. }
  26.  
  27. size_t pos = 0;
  28. while (std::string::npos != (pos = xml.find_first_of(reserved_chars, pos)))
  29. {
  30. xml.replace(pos, 1, transformations[xml[pos]]);
  31. pos++;
  32. }
  33.  
  34. std::cout << xml << "\n";
  35.  
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 2968KB
stdin
Standard input is empty
stdout
a < > & ' " string
a &lt; &gt; &amp; &apos; &quot; string