我试图在 C++ 中将十六进制数转换为十进制数

Im trying to convert a hexadecimal number to decimal number in C++

这是我目前拥有的:

#include <iostream>
#include <cmath>
#include <string.h>
using namespace std;


int main() {
    string hexa = "1A";
    
//  cout<<"HEXADECIMAL TO DECIMAL\n";
//  cout<<"ENTER HEXADECIMAL: ";
//  cin>>hexa;  
    
//  int inc1 = 0, hex1, ans, total = 0;
                            
    int a=0, b=1, ans, count=0, total, size=hexa.length();
    //count also increment
    
    for (int i=0; i<hexa.length(); i++){
        if(hexa[i] == 'A'){
            ans = 10 * pow(16, i);
        } else {
            ans = hexa[i] * pow(16, i);
        }
        total = total + ans;
    }
    
    cout<<"ANSWER IS: " <<total;    
/**
    do{
    hex1 = hexa % 10;
    ans = hex1 * pow(16, inc1);
    inc1++;
    total = total + ans;
    hexa = hexa / 10;
    } while (hexa!=0);
    
    
**/
}

我可以在网上偷一些代码,但我不想作弊(我的老师开始怀疑我了)。注释中的代码有效,带有 do-while 循环的代码但它仅适用于纯数字输入。我正在努力创建一个接受字母输入的代码。另外,我不允许使用那些花哨的功能等等。

#include <iostream>
#include <string>
using namespace std;

int main(){
  string s;
  cin>>s;//input string
  int ans=0;//for storing ans
  int p=1;
  int n=s.size();//length of the string
  //travarsing from right to left
  for(int i=n-1;i>=0;i--){
    //if the character is between 0 to 9
    if(s[i]>='0'&&s[i]<='9'){
        ans=ans+p*(s[i]-'0');           
    }
    //if the character is between A to F
    else{
            ans=ans+p*(s[i]-'A'+10);
    }
  p=p*16;                
  }
  cout<<ans;
  return 0;
}