0

I am new to programing and I was wondering if someone could help me understand why I am getting this error. Also the code works when it is in main, but not when I try to use it as a function call. Any other tips would be appreciated too.

    void hex2Dec()
    {
        string hex;
        getline(cin,hex);
        double con[3];
        double decimal;

        cout << "Hex # " << hex << " was entered." << endl;
        for (int n = 0; n < 4; n++)
        {
            if (int(hex[n] > 47 && int(hex[n]) < 58))
            {
                con[n] = (int(hex[n]) - 48) * pow(16, 3 - n);
            }``
            else (int(hex[n]) > 96 && int(hex[n]) < 122)
            {
                con[n] = (int(hex[n]) - 87) * pow(16, 3 - n);
            }

        }
        decimal = con[0] + con[1] + con[2] + con[3];
        cout << "The hex # " << hex << " = " << decimal << " in decimal." << endl;
  • 1
    `for (int n = 0; n < 4; n++)` It looks like you need `con` to be an array with at least 4 elements. – R Sahu Mar 07 '20 at 03:31
  • The expression "`int(hex[n] > 47 && int(hex[n]) < 58)`" makes no sense in C++. What are you trying to accomplish here? `pow(16, 3 - n)` -- you'll be surprised to learn that `pow(16, 2)`, for example, is not 256, because [floating point math is broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). Any integer arithmetic that makes use of `pow()` is logically broken. If the entered string is 3 character or less in size, the shown code results in undefined behavior, possibly a crash. You have multiple problems with the shown code. – Sam Varshavchik Mar 07 '20 at 03:31
  • Thanks that all makes sense. I got rid of pow(), but my program still crashes. C++ is telling me that I am trying to cast a 4 byte value to a 8 byte value and that I need to cast it to a wider type. Any thoughts on what I Should do? – Bailey Downing Mar 07 '20 at 03:54

0 Answers0