IsDouble is a check code snippet to check if a std::string or AnsiString can be converted to a double.
IsDouble is shown in two flavors:
- IsDouble for std::string
- IsDouble for AnsiString
For std::strings, CanCast and CanLexicalCast are more general versions of IsDouble.
IsDouble for std::string
#include <cassert> #include <sstream> //From http://www.richelbilderbeek.nl/CppIsDouble.htm bool IsDouble(const std::string& s) { std::istringstream i(s); double temp; return ( (i >> temp) ? true : false ); } //From http://www.richelbilderbeek.nl/CppIsDouble.htm bool IsDouble(const std::string& s, double& rDouble) { std::istringstream i(s); if (i >> rDouble) { return true; } rDouble = 0.0; return false; } int main() { assert(IsDouble("123.456")==true); assert(IsDouble("abcdefg")==false); double d = 0.0; if (IsDouble("3.14",d) == true) { assert(d==3.14); } }
IsDouble for AnsiString
This code compiles cleanly under C++ Builder 6.0
//From http://www.richelbilderbeek.nl/CppIsDouble.htm const bool IsDouble(const AnsiString& s) { try { s.ToDouble(); return true; } catch (EConvertError& e) { return false; } } //From http://www.richelbilderbeek.nl/CppIsDouble.htm const bool IsDouble(const AnsiString& s, double& rDouble) { try { rDouble = s.ToDouble(); return true; } catch (EConvertError& e) { rDouble = 0.0; return false; } }