fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4. #include <vector>
  5.  
  6. std::string s1 = "[1 -2.5 3;4 5.25 6;7 8 9.12]";
  7.  
  8. std::string cutter(std::string &s){
  9. std::string res = "";
  10. for (auto c : s) // Loop over all chars in s
  11. {
  12. if (c == ';') res += ' '; // Replace ; with space
  13. else if ((c != '[') && (c != ']')) res += c; // Skip [ and ]
  14. }
  15. return res;
  16. }
  17.  
  18. std::vector<float> string_to_floats(std::string &s)
  19. {
  20. float f;
  21. std::vector<float> res;
  22.  
  23. std::stringstream stream(s); // Create and initialize the stream
  24. while(1)
  25. {
  26. stream >> f; // Try to read a float
  27. if (stream.fail()) return res; // If it failed, return the result
  28. res.push_back(f); // Save the float
  29. }
  30. }
  31.  
  32. int main()
  33. {
  34. std::string s2 = cutter(s1);
  35. std::cout << s2 << std::endl;
  36.  
  37. std::vector<float> values = string_to_floats(s2);
  38. std::cout << "Number of floats: " << values.size() << std::endl;
  39. for (auto f : values) std::cout << f << std::endl;
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
1 -2.5 3 4 5.25 6 7 8 9.12
Number of floats: 9
1
-2.5
3
4
5.25
6
7
8
9.12