Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.22 KB | None | 0 0
  1. #include <cerrno>
  2. #include <cmath>
  3. #include <cstdio>
  4. #include <cstring>
  5. #include <limits>
  6. #include <stdexcept>
  7.  
  8. float str2f(std::string const &str, bool rethrow, float def) {
  9.   if (str.empty()) {
  10.     return def;
  11.   }
  12.   char *ep;
  13.   errno = 0;
  14.   double rtn = strtod(str.c_str(), &ep);
  15.   if ((rtn > std::numeric_limits<float>::max()) ||
  16.       (rtn < -std::numeric_limits<float>::max()) ||
  17.       ((rtn > 0) && (rtn < std::numeric_limits<float>::min())) ||
  18.       ((rtn < 0) && (rtn > -std::numeric_limits<float>::min()))) {
  19.     if (rethrow) {
  20.       throw std::out_of_range(str + " is too large for a float.");
  21.     }
  22.   } else if (errno || (*ep != '\0')) {
  23.     if (rethrow) {
  24.       if (errno) {
  25.         throw std::invalid_argument(std::string(strerror(errno)));
  26.       }
  27.       throw std::invalid_argument(std::string("Failed to parse: ") + str +
  28.                                   " as float.");
  29.     }
  30.     return def;
  31.   }
  32.   return rtn;
  33. }
  34.  
  35. void chomp(std::string &str) {
  36.   size_t lnf = str.find_last_not_of("\r\n");
  37.   if(lnf != std::string::npos){
  38.     str = str.substr(0, lnf+1);
  39.   }
  40. }
  41.  
  42. std::vector<std::string> SplitStringByDelim(std::string const &inp,
  43.                                             char const *delim,
  44.                                             bool PushEmpty,
  45.                                             bool chompInput) {
  46.   std::string inpCpy = inp;
  47.   if(chompInput){
  48.     chomp(inpCpy);
  49.   }
  50.   size_t nextOccurence = 0;
  51.   size_t prevOccurence = 0;
  52.   std::vector<std::string> outV;
  53.   bool AtEnd = false;
  54.   while (!AtEnd) {
  55.     nextOccurence = inpCpy.find_first_of(delim, prevOccurence);
  56.     if (nextOccurence == std::string::npos) {
  57.       if (prevOccurence == inpCpy.length()) {
  58.         break;
  59.       }
  60.       AtEnd = true;
  61.     }
  62.     if (PushEmpty || (nextOccurence != prevOccurence)) {
  63.       outV.push_back(
  64.           inpCpy.substr(prevOccurence, (nextOccurence - prevOccurence)));
  65.     }
  66.     prevOccurence = nextOccurence + 1;
  67.   }
  68.   return outV;
  69. }
  70.  
  71. std::vector<double> StringVToDoubleV(std::vector<std::string> const &stringV) {
  72.   std::vector<double> outV;
  73.   size_t end = stringV.size();
  74.   for (size_t it = 0; it < end; ++it) {
  75.     outV.push_back(str2d(stringV[it], true));
  76.   }
  77.   return outV;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement