Hexadecimal calculator run time error

I'm trying to get this thing to work correctly but I just can't. For example, it adds hexadecimals like F + F = 000000001E (which I think is correct, right?) but if I try to add 1D + 1D once I enter the first decimal number (1D) it doesn't let me enter the second one (1D) and outputs that the sum is 000000002E.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

#include <iostream>
using namespace std;

void output(char number[]);
void hex_sum(char hex1[], char hex2[], char sum[]);

int main()
{
  char answer;

  do
    {

      char hex1[10] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
      char hex2[10] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
      char sum[10] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};

      cout << "Enter the first hexadecimal number: \n";
      cin >> hex1[0];
      cout << "Enter the second hexadecimal number: \n";
      cin >> hex2[0];

      hex_sum(hex1, hex2, sum);

      cout << "The sum is: \n";

      for(int i = 9; i >=0; i--)
    {
      cout << sum[i];
    }

      cout << "\n" << "Would you like to try again? (Y/N)?\n";
      cin >> answer;

    } while(answer == 'Y' || answer == 'y');

    cout << "Good-bye! \n";

    return 0;
}

void hex_sum(char hex1[], char hex2[], char sum[])
{
  int x, y;
  int carry = 0;
  int other_carry = 0;

    for(int i = 0; i < 10; i++)
    {
        if('0' <= hex1[i] && hex1[i] < '0' + 10)
            x = hex1[i] - '0';

        else
            x = hex1[i] - 'A' + 10;

        if('0' <= hex2[i] && hex2[i] < '0' + 10)
            y = hex2[i] - '0';

        else
            y = hex2[i] - 'A' + 10;

        carry = other_carry;

    int z;

        z = (x + y + carry) % 16;
        other_carry = (x + y + carry) / 16; 

        if(0 <= z && z < 10)
            sum[i] = char('0' + z);

        else if(10 <= z && z < 16)
            sum[i] = char('A' + z - 10);
    }

    if(1 == carry && 1 == other_carry)
        cout << "Addition overflow.\n";
}


If I removed the [0] from

1
2
3
4
cout << "Enter the first hexadecimal number: \n";
cin >> hex1[0];
cout << "Enter the second hexadecimal number: \n";
cin >> hex2[0];


it lets me enter the second 1D but outputs that the result of 1D + 1D is 00000000A2, instead of 000000003A. If I do that, the output for hexadecimals made out of only one letter like F + F is also wrong. Instead of F + F = 000000001E, I get 000000000E.

Topic archived. No new replies allowed.