-4

I think there's some problem in my vs code I am new to this coding stuff even after writing the correct code it gives me wrong results in almost every second code I write i get uncertain results Plz guys help me with this , plz check running this code in your machine....

#include <iostream>
using namespace std;
int main()
{

    char a[30];
    cout << "enter the hexadecimal";
    cin >> a;
    int i = 0, c, digit, decimal = 0, p = 1;
    while (a[i] != '\0') {
        i++;
    }
    for (int j = i; j >= 0; j--) {
        c = a[j];
        if (c >= 48 && c <= 57) {
            digit = c - 48;
        }
        else if (c >= 97 && c <= 112) {
            digit = c - 87;
        }
        decimal += digit * p;
        p *= 8;
    }
    cout << "\ndecimal is " << decimal;
    return 0;
}

while entering hexa decimal plz only enter small alphabets i have not taken capital letters into consideration

for cheking hexadecimal to decimal use this site https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=146

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 1
    Well, what did you observe, when stepping through your code line by line with the debugger? Were all variables chaning as you expect they should do? – πάντα ῥεῖ Apr 11 '21 at 20:18
  • What is the input it fails on? What is the output when it fails? Consider using character literals like `'0'`, `'9'`, `'a'`, `'z'` to make your code easier to read since the intent is more clear. – Retired Ninja Apr 11 '21 at 20:21
  • bro i don't know how to do that but what did was after every statement where the values were changing I wrote a cout for that variable and every thing seemed to be perfect but the final result came wrong... – Broken Brain Apr 11 '21 at 20:22
  • retired ninja for the input 1a5 it should give 421 but it gives something very wrong – Broken Brain Apr 11 '21 at 20:23
  • I have converted the string to ascii code and from there used the integer value since 0-9 char will give the ascii code from 48-57 so I subtracted 48 from the result to get the digit required – Broken Brain Apr 11 '21 at 20:24

1 Answers1

1

There are several problems with the code, but I think that the main one is that you are multiplying p by 8 when it should be 16 (as hex is base-16, not base-8).

You also should take care with invalid inputs. What happens if someone enters an invalid letter 'j' for instance?

Besides, when you calculate the initial length of the string, you are setting ito the position of the array with a '\0' value so when you start processing the input, a[i] is 0 and that leads to using an uninitialized variable (digit has not been assigned a value, this is related to the previous "invalid input" issue).

By the way, I would also use chars in the comparisions instead of ASCII codes, it's easier to see what you are looking for:

    if (c >= '0' && c <= '9') {
        digit = c - '0';
    }

and so on...

Ion Larrañaga
  • 464
  • 2
  • 5