Skip to content

Latest commit

 

History

History
89 lines (51 loc) · 4.29 KB

CppIsDouble.md

File metadata and controls

89 lines (51 loc) · 4.29 KB

 

 

 

 

 

 

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:

 

For std::strings, CanCast and CanLexicalCast are more general versions of IsDouble.

 

 

 

 

 

 


#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);   } }

 

 

 

 

 

 

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;   } }