1
0
Fork 0

Validate string to double using std::isfinite

This commit is contained in:
krcroft 2020-03-31 10:31:08 -07:00 committed by Patryk Obara
parent 239396fec8
commit 75dd033cb0
3 changed files with 26 additions and 16 deletions

View file

@ -23,8 +23,11 @@
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <ctype.h>
#include <limits>
#include <stdexcept>
#include <string.h>
#include <string>
@ -35,8 +38,26 @@
#define strncasecmp(a, b, n) _strnicmp(a, b, n)
#endif
// Convert a string to double, returning true or false depending on susccess
bool str_to_double(const std::string& input, double &value);
/*
* Converts a string to a finite number (such as float or double).
* Returns the number or quiet_NaN, if it could not be parsed.
* This function does not attemp to capture exceptions that may
* be thrown from std::stod(...)
*/
template<typename T>
T to_finite(const std::string& input) {
T result = std::numeric_limits<T>::quiet_NaN();
size_t bytes_read = 0;
try {
const double interim = std::stod(input, &bytes_read);
if (!input.empty() && bytes_read == input.size())
result = static_cast<T>(interim);
}
// handle exceptions that stod may throw
catch (std::invalid_argument e) {}
catch (std::out_of_range e) {}
return result;
}
// Returns the filename with the prior path stripped.
// Works with both \ and / directory delimeters.