From a8fe2634ca517cc8fa8aa9b2e5734cb324895e37 Mon Sep 17 00:00:00 2001 From: Jason Felds Date: Sat, 4 May 2013 13:43:54 -0400 Subject: [PATCH] Do string validation before parsing. ...this is NOT the right place for this. At some point, we need to either use std::stof directly and/or just accept that we need to use exceptions. --- src/RageUtil.cpp | 22 +++++++++++++++------- src/RageUtil.h | 4 +++- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/RageUtil.cpp b/src/RageUtil.cpp index dacf2e49bf..f7b71851c9 100644 --- a/src/RageUtil.cpp +++ b/src/RageUtil.cpp @@ -1753,19 +1753,27 @@ void MakeLower( wchar_t *p, size_t iLen ) float StringToFloat( const RString &sString ) { - float ret = strtof( sString, nullptr ); - - if( !isfinite(ret) ) - ret = 0.0f; - return ret; + RString toTrim = sString; + Trim(toTrim); + if (toTrim.size() == 0) + { + return 0; + } + return std::stof(toTrim); } bool StringToFloat( const RString &sString, float &fOut ) { + RString toTrim = sString; + Trim(toTrim); + if (toTrim.size() == 0) + { + return false; + } char *endPtr; - fOut = strtof( sString, &endPtr ); - return sString.size() && *endPtr == '\0' && isfinite( fOut ); + fOut = strtof( toTrim, &endPtr ); + return *endPtr == '\0' && isfinite( fOut ); } RString FloatToString( const float &num ) diff --git a/src/RageUtil.h b/src/RageUtil.h index a44739f45a..426018da69 100644 --- a/src/RageUtil.h +++ b/src/RageUtil.h @@ -406,7 +406,10 @@ void MakeLower( char *p, size_t iLen ); void MakeUpper( wchar_t *p, size_t iLen ); void MakeLower( wchar_t *p, size_t iLen ); +// TODO: Have the three functions below be moved to better locations. float StringToFloat( const RString &sString ); +bool StringToFloat( const RString &sString, float &fOut ); + /** * @brief Have a standard way of converting floats to strings. * @@ -414,7 +417,6 @@ float StringToFloat( const RString &sString ); * @param num the number to convert. * @return the string as trimmed as it can be. */ RString FloatToString( const float &num ); -bool StringToFloat( const RString &sString, float &fOut ); RString WStringToRString( const wstring &sString ); RString WcharToUTF8( wchar_t c );