fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <sstream>
  4.  
  5. std::vector<int> read_integers(std::istream & input)
  6. {
  7. std::vector<int> numbers;
  8.  
  9. int number = 0;
  10. bool have_number = false;
  11.  
  12. char c;
  13.  
  14. // Loop until reading fails.
  15. while (input.get(c)) {
  16. if (c >= '0' && c <= '9') {
  17. // We have a digit.
  18. have_number = true;
  19.  
  20. // Add the digit to the right of our number. (No overflow check here!)
  21. number = number * 10 + (c - '0');
  22. } else if (have_number) {
  23. // It wasn't a digit and we started on a number, so we hit the end of it.
  24. numbers.push_back(number);
  25. have_number = false;
  26. number = 0;
  27. }
  28. }
  29.  
  30. // Make sure if we ended with a number that we return it, too.
  31. if (have_number) { numbers.push_back(number); }
  32.  
  33. return numbers;
  34. }
  35.  
  36. int main() {
  37. auto const input_string = std::string("12f 356 48 r56 fs6879 57g 132e efw ddf312 323f");
  38. std::istringstream input_stream(input_string);
  39.  
  40. std::cout << "Input: " << input_string << std::endl;
  41.  
  42. auto ints = read_integers(input_stream);
  43.  
  44. std::cout << "Output:" << std::endl;
  45.  
  46. for (auto i = ints.begin(); i != ints.end(); ++i) {
  47. std::cout << "* " << *i << std::endl;
  48. }
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
Input: 12f 356 48 r56 fs6879 57g 132e efw ddf312 323f
Output:
* 12
* 356
* 48
* 56
* 6879
* 57
* 132
* 312
* 323