Let us say that we have taken an integer, 1234, and split into two parts: 12 and 34:
int part_1 = 12;
int part_2 = 34;
To sum or add, we can use the addition operator:
int sum = part_1 + part_2;
cout << "Sum is: " << sum << endl;
Edit 1: Playing with digits
In many cases when the requirements require manipulation of digits, keeping the number as text or a string is often easier.
Let us have a string:
const std::string text_number = "1234";
We can obtain the length of the string:
const unsigned int length = text_number.length();
To split the string in half, we divide the length in half, then copy half of the characters to one string and half to another.
const unsigned int half_length = length / 2;
std::string part1;
std::string part2;
unsigned int index;
for (index = 0; index < half_length; ++index)
{
part1 += text_number[index];
}
for (; index < length; ++index)
{
part2 += text_number[index];
}
Now, the trick is to convert the text strings into internal number representation. One method is to use istringstream
;
std::istringstream stream1(part1);
std::istringstream stream2(part2);
int first_half;
int second_half;
stream1 >> first_half;
stream2 >> second_half;
Finally, they can be summed:
int sum = first_half + second_half;
3
solved C++ Separate an INT and Sum it’s halves