add 2 string number in c++

I have no idea why I can't compile my file

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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// NOTE: The ONLY files that should be #included for this assignment are iostream, vector, and string
// No other files should be #included

#include <iostream>
#include <vector>
#include <string>

// NOTE: The ONLY files that should be #included for this assignment are iostream, vector, and string
// No other files should be #included


using namespace std;

string addbin(string, string);
string addhex(string, string);


int main()
{

  cout << "binary 1101 + 1000 = " << addbin("1101", "1000") << endl;   //you should get 10101
  cout << "binary 11000 + 1011 = " << addbin("11000", "1011") << endl; //you should get 100011
  cout << "binary 11111111 + 1 = " << addbin("11111111", "1") << endl; //you should get 100000000
  cout << "binary 101010 + 10 = " << addbin("101010", "10") << endl << endl; //you should get 101100

  cout << "hexadecimal A4 + A5 = " << addhex("A4", "A5") << endl;  //you should get 149
  cout << "hexadecimal 2B + C = " << addhex("2B", "C") << endl;    //you should get 37
  cout << "hexadecimal FABC + 789 = " << addhex("FABC", "789") << endl;  //you should get 10245
  cout << "hexadecimal FFFFFF + FF = " << addhex("FFFFFF", "FF") << endl << endl; //you should get 10000FE


  system("PAUSE");
  return 0;

}


string addbin(string bin1, string bin2)
{
  string result = "";
  int blength1 = bin1.length();
  int blength2 = bin2.length();
  int bsum;
  int carry = 0;
  int length;
  int a = 0;
  int b = 0;




  if (bin1 < bin2)
  {
    for (int i = 0; i < blength2 - blength1; i++)
      bin1 = '0' + bin1;
  }

  if (bin2 < bin1)
  { 
    for (int i = 0; i < blength1 - blength2; i++)
      bin2 = '0' + bin2;
  }

  for (int i = 0; i < blength1; i++)
  {
    int a = int(bin1[bin1.length()]) - 48;
  }

  for (int i = 0; i < blength2; i++)
  {
    int b = int(bin2[bin2.length()]) - 48;
  }

  if (blength1 > blength2)
  {
    length = blength1;
  }

  else
  {
    length = blength2;
  }


  for (int i = length - 1; i >= 0; i--)
  {
    bsum = carry + a + b;

    if (bsum == 0)
    {
      carry = 0;
      result = "0" + result;
    }

    else if (bsum == 1)
    {
      carry = 0;
      result = "1" + result;
    }

    else if (bsum == 2)
    {
      carry = 1;
      result = "0" + result;
    }

    else if (bsum = 3)
    {
      carry = 1;
      result = "1" + result;
    }
  }

  if (carry = 1)
  {
    result = "1" + result;
  }
    return result;
}

string addhex(string hex1, string hex2)
{
  return 0;
}
Last edited on
the result is not correct.. I think there is some problem in my string addbin function
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
#include <iostream>
#include <string>

void make_same_size( std::string& a, std::string& b )
{
    while( a.size() < b.size() ) a = '0' + a ;
    while( b.size() < a.size() ) b = '0' + b ;
}

std::string reverse( std::string str ) { return { str.rbegin(), str.rend() } ; }

// invariant: strings a and b consist solely of characters '0' and '1'
std::string addbin( std::string a, std::string b )
{
    make_same_size( a, b ) ;
    if( a.empty() ) return "0" ;

    a = reverse(a) ;
    b = reverse(b) ;
    std::string result ;
    int carry = 0 ;

    for( std::size_t i = 0 ; i < a.size() ; ++i )
    {
        const int aa = a[i] - '0' ;
        const int bb = b[i] - '0' ;
        const int rr = ( aa + bb + carry ) ;
        carry = rr / 2 ;
        result += char( rr%2 + '0' ) ;
    }

    if( carry == 1 ) result += '1' ;

    return reverse(result) ;
}

int main()
{
  std::cout << "binary 1101 + 1000 = " << addbin("1101", "1000") << '\n'   //you should get 10101
            << "binary 11000 + 1011 = " << addbin("11000", "1011") << '\n' //you should get 100011
            << "binary 11111111 + 1 = " << addbin("11111111", "1") << '\n' //you should get 100000000
            << "binary 101010 + 10 = " << addbin("101010", "10") << '\n' //you should get 101100
            << "binary 0 + 0 = " << addbin("0", "0") << "\n\n" ; // 0
}

http://coliru.stacked-crooked.com/a/c4286dd063288011
thank you my friend but now I have another problem with adding string hex number.
I think the problem I have is converting the letter A,B,C,D,E,F. I have checked that online those characters need to -58 to get the interger.

if(hex1[hex1.hlength1()] == 'A' || 'B' || 'C'|| 'D' || 'E' || 'F' )
{
for (int i = length - 1; i >= 0; i--)
{
hsum = carry + (hex1[i] - 58) + (hex2[i] - 58);
}
}
else
{
for (int i = length - 1; i >= 0; i--)
{
hsum = carry + (hex1[i] - '0') + (hex2[i] - '0');
}
I have no idea how to check hex1 and hex2 in the same condition but that if/else statement is not working.
> I have checked that online those characters need to -58 to get the interger.

The only guarantee that we have is that for the characters representing the ten decimal digits,
starting with '0', the value of each character is one greater than the value of the previous character.
ie. '1' == char( '0' + 1 ), '2' == char( '1' + 1 ) etc. up to '9' == char( '8' + 1 )

Other than that, the values of the characters are locale specific.
In particular, there is no guarantee that 'B' == char( 'A' + 1 )

The sane thing to do is to look up the values for 'A', 'B' etc. in a look-up table.

Something like this:

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
#include <iostream>
#include <string>

void make_same_size( std::string& a, std::string& b )
{
    while( a.size() < b.size() ) a = '0' + a ;
    while( b.size() < a.size() ) b = '0' + b ;
}

std::string reverse( std::string str ) { return { str.rbegin(), str.rend() } ; }

const std::string hex_digits = "0123456789ABCDEF0123456789abcdef" ;

int hexchar_to_int( char h ) { return hex_digits.find(h) % 16 ; }

char int_to_hexchar( int d ) { return hex_digits[d] ; }

// invariant: strings a and b consist solely of hex digits
std::string addhex( std::string a, std::string b )
{
    make_same_size( a, b ) ;
    if( a.empty() ) return "0" ;

    a = reverse(a) ;
    b = reverse(b) ;
    std::string result ;
    int carry = 0 ;

    for( std::size_t i = 0 ; i < a.size() ; ++i )
    {
        const int aa = hexchar_to_int( a[i] ) ;
        const int bb = hexchar_to_int( b[i] ) ;
        const int rr = ( aa + bb + carry ) ;
        carry = rr / 16 ;
        result += int_to_hexchar(rr%16) ;
    }

    if( carry != 0 ) result += int_to_hexchar(carry) ;

    return reverse(result) ;
}

int main()
{
  std::cout << "hexadecimal A4 + a5 = " << addhex("A4", "a5") << '\n'  //you should get 149
            << "hexadecimal 2B + C = " << addhex("2B", "C") << '\n'    //you should get 37
            << "hexadecimal fabc + 789 = " << addhex("fabc", "789") << '\n'  //you should get 10245
            << "hexadecimal FFFFFF + ff = " << addhex("FFFFFF", "ff") << "\n\n" ; //you should get 10000FE
}

http://coliru.stacked-crooked.com/a/4be457eefb58fceb
thank you so much.
Tbh, I don't really understand your code because I am pretty new to c++. All I want to know is how to set up the function if the character in (string hex1 or string hex2) are A,B,C,D,E or F -58, otherwise, for the character '0' to '9' - '0'. Can you tell me make the improvement based on my code??


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
string result = "";
  int hlength1 = hex1.length();
  int hlength2 = hex2.length();
  int hsum;
  int carry = 0;
  int length;
  int a;
  int b;

  if (hex1 < hex2)
  {
    for (int i = 0; i < hlength2 - hlength1; i++)
      hex1 = '0' + hex1;
  }

  if (hex2 < hex1)
  {
    for (int i = 0; i < hlength1 - hlength2; i++)
      hex2 = '0' + hex2;
  }

  if (hlength1 > hlength2)
  {
    length = hlength1;
  }

  else
  {
    length = hlength2;
  }
//  this is the part that I don't understand
  for (int i = length - 1; i >= 0; i--)
  {
    if (hex1[i] == 'A' || 'B' || 'C' || 'D' || 'E' || 'F')
    {
    int a = hex[i] - 58;
    }
    else
    {
     int a = hex[i] - '0';
    }

    if (hex2[i] == 'A' || 'B' || 'C' || 'D' || 'E' || 'F')
    {
    int a = hex[i] - 58;
    }
    else
    {
     int a = hex[i] - '0';
    }
    hsum = carry + a + b;

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
#include <iostream>
#include <string>

// get the integer value of hex char 'h'
int hexchar_to_int( char h )
{
    // if h is also a decimal digit
    if( h >= '0' && h <= '9' ) return h - '0' ;

    switch(h) // h is one of A, B, C, D, E, F
    {
        case 'A' : case 'a' : return 10 ;
        case 'B' : case 'b' : return 11 ;
        case 'C' : case 'c' : return 12 ;
        case 'D' : case 'd' : return 13 ;
        case 'E' : case 'e' : return 14 ;
        case 'F' : case 'f' : return 15 ;
    }

    return -1 ; // invalid hex char
}

// get the hex character with value d
char int_to_hexchar( int d )
{
    // if d is also a decimal digit
    if( d >= 0 && d <= 9 ) return d + '0' ;

    switch(d) // d is one of 10, 11, 12, 13, 14, 15
    {
        case 10 : return 'A' ;
        case 11 : return 'B' ;
        case 12 : return 'C' ;
        case 13 : return 'D' ;
        case 14 : return 'E' ;
        case 15 : return 'F' ;
    }

    return '*' ; // invalid hex digit value
}
// invariant: strings a and b consist solely of hex digits
std::string addhex( std::string hex1, std::string hex2 )
{
    // make hex1 and hex2 have the same_size (pad with '0' on the left)
    while( hex1.size() < hex2.size() ) hex1 = '0' + hex1 ;
    while( hex2.size() < hex1.size() ) hex2 = '0' + hex2 ;

    if( hex1.empty() ) return "0" ; // hex1 and hex2 are two empty strings

    std::string result ;
    int carry = 0 ;

    for( int i = hex1.size() - 1 ; i >= 0 ; --i )
    {
        const int a = hexchar_to_int( hex1[i] ) ;
        const int b = hexchar_to_int( hex2[i] ) ;

        const int hsum = carry + a + b ;

        carry = hsum / 16 ;
        result = int_to_hexchar(hsum%16) + result ;
    }

    if( carry != 0 ) result = int_to_hexchar(carry) + result ;

    return result ;
}

int main()
{
  std::cout << "hexadecimal A4 + a5 = " << addhex("A4", "a5") << '\n'  //you should get 149
            << "hexadecimal 2B + C = " << addhex("2B", "C") << '\n'    //you should get 37
            << "hexadecimal fabc + 789 = " << addhex("fabc", "789") << '\n'  //you should get 10245
            << "hexadecimal FFFFFF + ff = " << addhex("FFFFFF", "ff") << "\n\n" ; //you should get 10000FE
}

http://coliru.stacked-crooked.com/a/2a426ce25a638d10
thank you so much, I have a question about const int a, const int b, and also const int hsum.
why do you put const in front of them?
> const int a, const int b, and also const int hsum. why do you put const in front of them?

Essentially it says that once initialised, these values should not be modified later; (and that the compiler should catch and generate an error if there is any attempt to modify them).

Here, this is just pure programming hygiene: instinctively, add the const-qualifier unless there is a conscious intent to modify the value later. (This is something you will have to learn on your own; the archetypal career teacher is not aware of such nuances.)

Sutter and Alexandrescu in 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices'
15. Use const proactively.

Summary

const is your friend. Immutable values are easier to understand, track, and reason about, so prefer constants over variables wherever it is sensible and make const your default choice when you define a value. It's safe, it's checked at compile time, and it's integrated with C++'s type system. ...

Discussion

Constants simplify code because you only have to look at where the constant is defined to know its value everywhere. Consider this code:
1
2
3
4
5
void Fun( vector<int>& v)
{  //...
   const size_t len = v.size();
   //... 30 more lines ...
}

When seeing len's definition above, you gain instant confidence about len's semantics throughout its scope (assuming the code doesn't cast away const, which it should not do). It's a snapshot of v's length at a specific point. Just by looking up one line of code, you know len's semantics over its whole scope. Without the const, len might be later modified, either directly or through an alias. Best of all, the compiler will help you ensure that this truth remains true.
...
Last edited on
Topic archived. No new replies allowed.