diff options
| -rw-r--r-- | src/helpers.cpp | 45 | ||||
| -rw-r--r-- | src/helpers.hpp | 4 |
2 files changed, 49 insertions, 0 deletions
diff --git a/src/helpers.cpp b/src/helpers.cpp index 796aa2e..7ae21c9 100644 --- a/src/helpers.cpp +++ b/src/helpers.cpp @@ -2,6 +2,7 @@ #include "helpers.hpp" #include <cerrno> +#include <cmath> #include <cstdlib> #include <climits> @@ -113,3 +114,47 @@ STR2NUM_ERROR str2num(uint16_t &i, char const *s, int base) { return SUCCESS; } +STR2NUM_ERROR str2num(float &f, char const *s, char *&pEnd) { + float l; + errno = 0; + l = strtof(s, &pEnd); + if (errno == ERANGE && l == HUGE_VALF) { + return OVERFLOW; + } + if (errno == ERANGE && l == -HUGE_VALF) { + return UNDERFLOW; + } + if (*s == '\0' || *pEnd != '\0') { + return INCONVERTIBLE; + } + f = l; + return SUCCESS; +} + +STR2NUM_ERROR str2num(float &f, char const *s) { + char *end; + return str2num(f, s, end); +} + +STR2NUM_ERROR str2num(double &d, char const *s, char *&pEnd) { + char *end; + float l; + errno = 0; + l = strtod(s, &end); + if (errno == ERANGE && l == HUGE_VAL) { + return OVERFLOW; + } + if (errno == ERANGE && l == -HUGE_VAL) { + return UNDERFLOW; + } + if (*s == '\0' || *end != '\0') { + return INCONVERTIBLE; + } + d = l; + return SUCCESS; +} + +STR2NUM_ERROR str2num(double &d, char const *s) { + char *end; + return str2num(d, s, end); +} diff --git a/src/helpers.hpp b/src/helpers.hpp index a429416..a5c8089 100644 --- a/src/helpers.hpp +++ b/src/helpers.hpp @@ -11,5 +11,9 @@ STR2NUM_ERROR str2num(int32_t &i, char const *s, int base = 0); STR2NUM_ERROR str2num(uint32_t &i, char const *s, int base = 0); STR2NUM_ERROR str2num(int16_t &i, char const *s, int base = 0); STR2NUM_ERROR str2num(uint16_t &i, char const *s, int base = 0); +STR2NUM_ERROR str2num(float &f, char const *s); +STR2NUM_ERROR str2num(double &d, char const *s); +STR2NUM_ERROR str2num(float &f, char const *s, char *&pEnd); +STR2NUM_ERROR str2num(double &d, char const *s, char *&pEnd); #endif /* PKE_HELPERS_HPP */ |
