This code works fine, it allows me to convert a hexadecimal to a decimal. I used the ascii chart. I need to add exceptions when the user enters in something invalid such as 1g, 12Z, etc..
i'm not sure if the block below is correct, and i'm unsure of where exactly to place it in my code.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int hex2dec( std::string hex );
int hex2dec( std::string hex )
{
unsigned long result = 0;
for (unsigned int i=0; i<hex.length(); i++)
{
if (hex[i]>=48 && hex[i]<=57)
{
result += (hex[i]-48)*pow(16,hex.length()-i-1);
}
else if (hex[i]>=65 && hex[i]<=70)
{
result += (hex[i]-55)*pow(16,hex.length( )-i-1);
}
else if (hex[i]>=97 && hex[i]<=102)
{
result += (hex[i]-87)*pow(16,hex.length()-i-1);
}
}
return result ;
}
int main ()
{
string hex;
cout<<"Enter hexadecimal to convert to decimal: ";
cin>>hex;