I need to add an exception in this code, not sure how to do it.

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.

i think the way i would do it would be :

//This is my try catch block

try {
if ((hex > 69 ) && (hex < 91)){
throw 33;
}
if ((hex > 102) && (hex < 123))
{
throw 99;
}
}
catch(...){
cout<<"ERROR"<endl;
}


//This is 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;

cout<< hex2dec(hex);

return 0;
}
Last edited on
Topic archived. No new replies allowed.