Teddles
Teddles

Reputation: 3

Is there a way to store INT and strings in the same array?

I'm not sure how parsing works, nor have I been able to do it in C++.

I've created an algorithm that converts decimals to hexadecimals. The algorithm right now still outputs values bigger than 9, like 10 instead of A. The following function was supposed to deal with the issue but when I run it through, I can't store the normal 1-9 values with the As and Bs in the same array, which means I can't output them. I've been stuck on this for 2 days.

string hexValues(int remainder)
{
    string A = "A";
    string B = "B";
    string C = "C";
    string D = "D";
    string E = "E";
    string F = "F";

    if (remainder == 10)
    {
        return A;
    }
    else if (remainder == 11)
    {
        return B;
    }
    else if (remainder == 12)
    {
        return C;
    }
    else if (remainder == 13)
    {
        return D;
    }
    else if (remainder == 14)
    {
        return E;
    }
    else if (remainder == 15)
    {
        return F;
    }
}
 hexMod = userDecNumber4Hex % 16;
            if (hexMod > 9)
            {
                hexadecimalAnswer[y] = hexValues(hexMod);
            }
            else
            {
                hexadecimalAnswer[y] = hexMod;
            }


    while (userDecNumber4Hex != 0)
    {
        if (userDecNumber4Hex % 16 != 0)
        {
            hexMod = userDecNumber4Hex % 16;
            if (hexMod > 9)
            {
                hexadecimalAnswer[y] = hexValues(hexMod);
            }
            else
            {
                hexadecimalAnswer[y] = hexMod;
            }

            userDecNumber4Hex = (userDecNumber4Hex-hexMod)/ 16;
            y += 1;
        }
        else if (userDecNumber4Hex % 16 == 0)
        {
            userDecNumber4Hex = userDecNumber4Hex / 16; 
            if (userDecNumber4Hex > 9)
            {
                hexadecimalAnswer[y] = userDecNumber4Hex;
            }

        }

    }

the code is long so i wasn't really sure what to post but there are multiple arrays- but its just one of them that i need to have store the values getting from the hexValues function, while it already has int values

Upvotes: 0

Views: 145

Answers (1)

Arkajyoti Banerjee
Arkajyoti Banerjee

Reputation: 466

Since the integers in your hexadecimal number are only going to range between 0 and 9, you can store them as characters. At the same time, you can store A-F as characters as well. Therefore, instead return characters as the face values.

char hexValues (int remainder)
{
    if (remainder < 10)
        return '0' + remainder;
    else 
        return 'A' + (remainder - 10);
}

For full conversion, here's a good excuse to use Recursion:

string decToHex (int n)
{
     if (n < 16)
     {
         string s (1, decToHex (n));
         return s;
     }
     else 
         return decToHex (n / 16) + hexValues (n % 16);
}

Upvotes: 1

Related Questions