From 3a14d39a1419e23e96c9143eb25d38c5245292e2 Mon Sep 17 00:00:00 2001 From: Martchus Date: Sat, 22 Sep 2018 16:47:44 +0200 Subject: [PATCH] Add conversion from const char* to float/double Previously only conversion from std::string to float/double was possible. --- conversion/stringconversion.h | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/conversion/stringconversion.h b/conversion/stringconversion.h index 10b62aa..3571e0d 100644 --- a/conversion/stringconversion.h +++ b/conversion/stringconversion.h @@ -484,6 +484,33 @@ IntegralType stringToNumber(const CharType *string, unsigned char base = 10) return result; } +/*! + * \brief Converts the given null-terminated \a string to a number assuming \a string uses the specified \a base. + * \tparam FloatingType The data type used to store the converted value. + * \tparam CharType The character type. + * \throws A ConversionException will be thrown if the provided \a string is not a valid number. + * \remarks This function is using std::basic_stringstream interanlly and hence also has its limitations (eg. regarding + * \a base and types). + * \sa numberToString(), bufferToNumber() + * \todo Provide an alternative using std::expected (when switching to C++17). + */ +template > * = nullptr> +FloatingType stringToNumber(const CharType *string, unsigned char base = 10) +{ + std::basic_stringstream ss; + ss << std::setbase(base) << string; + FloatingType result; + if ((ss >> result) && ss.eof()) { + return result; + } + std::string errorMsg; + errorMsg.reserve(42 + std::char_traits::length(string)); + errorMsg += "The string \""; + errorMsg += string; + errorMsg += "\" is no valid floating number."; + throw ConversionException(errorMsg); +} + /*! * \brief Converts the given \a string of \a size characters to an unsigned numeric value using the specified \a base. * \tparam IntegralType The data type used to store the converted value.