: I was wondering if there was some existing functions maybe in the string library or any other popular one that would make this check easier, rather than a double for loop
From [[http://www.codepedia.com/1/CppHexStrIsInt]]:
#include <sstream>
#include <cassert>
///Checks whether a std::string containg hexadecimal
///can be converted to an int.
///Returns true if possible, also returning this integer by referencing.
///Returns false otherwise, setting the referenced int to zero.
bool IsHexInt(const std::string& s, int& rInt)
{
std::istringstream i(s);
i >> std::hex;
if (!(i >> rInt))
{
rInt = 0; return false;
}
return true;
}
int main()
{
int temp = -1;
assert(IsHexInt("0",temp) == true);
assert(IsHexInt("9",temp) == true);
assert(IsHexInt("A",temp) == true);
assert(IsHexInt("B",temp) == true);
assert(IsHexInt("C",temp) == true);
assert(IsHexInt("D",temp) == true);
assert(IsHexInt("E",temp) == true);
assert(IsHexInt("F",temp) == true);
assert(IsHexInt("-F",temp) == true);
assert(IsHexInt("-F85AE",temp) == true);
assert(IsHexInt("-F85AE",temp) == true);
assert(IsHexInt("FFFFFFF",temp) == true);
assert(IsHexInt("80000000",temp) == true); // MAX
assert(IsHexInt("80000001",temp) == false);
assert(IsHexInt("G",temp) == false);
assert(IsHexInt("G",temp) == false);
}
Although I noted that the range is not too big, the max is the std::string
80000000. For bigger ranges, I'd use AsmGuru's solution.
See ya
bilderbikkel