I need to check if an std::string
is a number. By number I mean either a whole number or a number with a decimal point (base 10).
I'm fine with the limits that long long
provides so anything outside that I don't care about. I don't have boost, but have copied the lexical_cast
.
It seems like casting to double
to verify a string does indeed work, but I'm wondering if there are any corner cases I'm not thinking of.
#include <typeinfo>
#include <sstream>
template<typename Out, typename In> static Out lexical_cast(In input)
{
stringstream ss;
ss << input;
Out r;
if ((ss >> r).fail() || !(ss >> std::ws).eof())
{
throw std::bad_cast();
}
return r;
}
bool is_numeric(const string in)
{
bool success = false;
try
{
lexical_cast<double>(in);
success = true;
}
catch(std::bad_cast &exc)
{
success = false;
}
return success;
}
EDIT
floating point number
I'm not using C++0x/C++11 so I can't use a regex to easily verify a floating point number. And I'm trying NOT to have to parse the string myself as that just means I have to have more unit tests to make sure I'm not missing anything.
With the NaN I know that they have the property float1 != float1
but GCC screws this up.