Advertisement
alansam

Strip non-numerics from string.

Aug 21st, 2022 (edited)
1,297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. /*
  2. If you have a    char c [ 10]= "x4ey3";
  3. How do you extract each integer and make them as integer data type each one??
  4.  */
  5.  
  6. #include <iostream>
  7. #include <iomanip>
  8. #include <string>
  9. #include <sstream>
  10. #include <algorithm>
  11. #include <vector>
  12. #include <cctype>
  13.  
  14. void fit_the_first(char const *);
  15.  
  16. //  print integers
  17. auto printegers = [](auto const & nums) {
  18.   for (auto ln = 1; auto nr : nums) {
  19.     std::cout << std::setw(3) << ln++
  20.               << ": "
  21.               << std::setw(5) << nr
  22.               << '\n';
  23.   }
  24. };
  25.  
  26. int main() {
  27.   char cc[] = "x4ey -  3 ; -44-";
  28.   fit_the_first(cc);
  29.  
  30.   return 0;
  31. }
  32.  
  33. void fit_the_first(char const * cc) {
  34.   std::string sc(cc);
  35.   std::cout << std::quoted(sc) << '\n';  //  display string
  36.  
  37.   // remove non-integer things from string by converting them to space
  38.   std::replace_if(sc.begin(), sc.end(), [](auto ch) {
  39.     return !(ch == '-' || ::isdigit(ch)); //  keep digits and -ve signs
  40.   }, ' ');
  41.   //  strip trailing whitespace
  42.   sc.erase(std::find_if(sc.rbegin(), sc.rend(), [](auto ch) {
  43.     return !::isspace(ch);
  44.   }).base(), sc.end());
  45.   std::cout << std::quoted(sc) << '\n';  //  display cleaned-up string
  46.  
  47.   //  load string into a stream
  48.   std::istringstream istr(sc);
  49.   int ival;
  50.   std::string word;
  51.  
  52.   //  read a number from the stream and store it in the vector
  53.   std::vector<int> nums;
  54.   while (!istr.eof()) {
  55.     istr >> word;
  56.     // try to read integers from word; discards widowed -ve signs
  57.     if (std::istringstream(word) >> ival) {
  58.       nums.push_back(ival);
  59.     }
  60.   }
  61.   //  on completion, vector contains all the integers in the string
  62.  
  63.   //  print integers
  64.   printegers(nums);
  65.  
  66.   return;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement