Darren Pan Darren Pan - 3 months ago 45
C++ Question

The addition of two hexadecimal numerals in c++

I'm writing a program that takes two hexadecimal numbers and converts them to decimal form, and prints out their sum in decimal form. The maximum length of the numbers is 10. {submit.cs.ucsb.edu/submission/203504}. I feel confuse about the error messages. The problem wants the max length of the numbers is 10. Why the output like "ffffffffff" works

#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

int hexToDecimal(string);
string decimalToHex(int);

int main()
{
long long hex1, hex2;

std::cout << "Enter first number:" << std::endl;
std::cin >> std::hex >> hex1;

std::cout << "Enter a second number:" << std::endl;
std::cin >> std::hex >> hex2;

if (hex1 >9999999999 || hex2 > 9999999999)

{
cout << "Addition Overflow" << endl;
}
else
{
std::cout << "The sum is "<< std::hex << hex1 + hex2 << "." << std::endl;

}


return 0;
}

Answer

There is a much simpler way to do this:

int hex1, hex2;

std::cout << "Enter first hex number:" << std::endl;
std::cin >> std::hex >> hex1;

std::cout << "Enter a second hex number:" << std::endl;
std::cin >> std::hex >> hex2;

std::cout << std::hex << hex1 + hex2 << std::endl;