From 33525908ed5480a914397cf57026c255a157c08a Mon Sep 17 00:00:00 2001 From: Andrew Bell Date: Thu, 2 Mar 2017 14:16:11 -0600 Subject: [PATCH] Handle characters that aren't numeric in string conversion. --- pdal/util/Utils.hpp | 66 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 15 deletions(-) diff --git a/pdal/util/Utils.hpp b/pdal/util/Utils.hpp index ce555971a5..9f5eda4d7e 100644 --- a/pdal/util/Utils.hpp +++ b/pdal/util/Utils.hpp @@ -52,6 +52,8 @@ #include #include +#include + #include "pdal_util_export.hpp" namespace pdal @@ -867,12 +869,23 @@ namespace Utils template<> inline bool fromString(const std::string& s, char& to) { - int i = std::stoi(s); - if (i >= std::numeric_limits::lowest() && - i <= std::numeric_limits::max()) + try { - to = static_cast(i); - return true; + int i = std::stoi(s); + if (i >= std::numeric_limits::lowest() && + i <= std::numeric_limits::max()) + { + to = static_cast(i); + return true; + } + } + catch (std::invalid_argument) // Character that isn't a number? + { + if (s.length() == 1) + { + to = s[0]; + return true; + } } return false; } @@ -888,13 +901,25 @@ namespace Utils inline bool fromString(const std::string& s, unsigned char& to) { - int i = std::stoi(s); - if (i >= std::numeric_limits::lowest() && - i <= std::numeric_limits::max()) + try { - to = static_cast(i); - return true; + int i = std::stoi(s); + if (i >= std::numeric_limits::lowest() && + i <= std::numeric_limits::max()) + { + to = static_cast(i); + return true; + } } + catch (std::invalid_argument) // Character that isn't a number? + { + if (s.length() == 1) + { + to = s[0]; + return true; + } + } + return false; } @@ -908,12 +933,23 @@ namespace Utils template<> inline bool fromString(const std::string& s, signed char& to) { - int i = std::stoi(s); - if (i >= std::numeric_limits::lowest() && - i <= std::numeric_limits::max()) + try { - to = static_cast(i); - return true; + int i = std::stoi(s); + if (i >= std::numeric_limits::lowest() && + i <= std::numeric_limits::max()) + { + to = static_cast(i); + return true; + } + } + catch (std::invalid_argument) // Character that isn't a number? + { + if (s.length() == 1) + { + to = s[0]; + return true; + } } return false; }