fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4. #include <vector>
  5.  
  6. template <typename parsed_type>
  7. std::vector<parsed_type> split(const std::string& text)
  8. {
  9. std::istringstream iss(text);
  10. std::vector<parsed_type> elements;
  11. parsed_type element;
  12.  
  13. while (iss >> element)
  14. elements.push_back(element);
  15.  
  16. return elements;
  17. }
  18.  
  19. template <typename container_type>
  20. void print_container(std::ostream& os, const container_type& c)
  21. {
  22. std::cout << '{';
  23. for (auto & item : c)
  24. std::cout << ' ' << item;
  25. std::cout << " }\n";
  26. }
  27.  
  28. int main()
  29. {
  30. std::string s("1 14 22 6 7");
  31. std::string words("alpha bravo charlie delta echo foxtrot golf");
  32.  
  33. print_container(std::cout, split<int>(s));
  34. print_container(std::cout, split<std::string>(words));
  35. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
{ 1 14 22 6 7 }
{ alpha bravo charlie delta echo foxtrot golf }