Advertisement
userxbw

Find delimiter and get other content C++

Oct 5th, 2022
963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5. #include <cstddef> // std::size_t
  6.  
  7. /* finddelim.cpp */
  8.  
  9. using std::cout; using std::cin; using std::cerr;
  10. using std::endl; using std::string; using std::vector;
  11. using std::ifstream;
  12. string readFileIntoString(const string path) {
  13.     ifstream input_file(path);
  14.     if (!input_file.is_open()) {
  15.         cerr << "Could not open the file - '"
  16.              << path << "'" << endl;
  17.         exit(EXIT_FAILURE);
  18.     }
  19.     string f= string((std::istreambuf_iterator<char>(input_file)), std::istreambuf_iterator<char>());
  20.     input_file.close();
  21.     return f;
  22. }
  23. vector<string> findDigits(string data)
  24. {
  25.     std::size_t pos;
  26.     string delim="-";
  27.     vector <string>numbers;
  28.   while ((pos = data.find(delim)) != string::npos) {
  29.         numbers.push_back(data.substr(0, pos));
  30.         data.erase(0, pos + delim.length());
  31.     }// get last numbera on tail if any
  32.     if(data.size()>0)
  33.     numbers.push_back(data);
  34. return numbers;
  35. }
  36. vector<string> removeEmpties(vector<string> v)
  37. {
  38.     auto isEmptyOrBlank = [](const std::string &s) {
  39.     return s.find_first_not_of(" \t") == std::string::npos;
  40.     };
  41.     v.erase(std::remove_if(v.begin(), v.end(),
  42.     isEmptyOrBlank), v.end());
  43. return v;
  44. }
  45. int main (){
  46. /* test file
  47. --242----2-343---3-33---943-3--3-5-223--848344-  */
  48. string filename="finddigits";
  49. string file_contents;
  50.     file_contents = readFileIntoString(filename);
  51.    cout << file_contents << endl;
  52.    vector<string>num=
  53.     removeEmpties(findDigits(readFileIntoString(filename)));
  54. for(const auto &n:num)
  55.     cout<< n <<" ";
  56.     cout<<endl;
  57. exit(EXIT_SUCCESS);
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement