I'm supposed to be writing a program that can convert a decimal number to binary. I have the code for the conversion working, but when I try to send an error when the user enters a number beyond the max/min for my type (unsigned short) using an if/else statement. When I enter what should be an invalid number the program jumps down to the conversion statement and either prints the max binary number (if entering something over 655355) or will go backwards counting down from the max (if entering in a negative number).
I thought wrote everything correctly.
#include <iostream>
#include <cmath>
#include <climits>
using namespace std;
// This converts the number to binary, it divides the imputed number by two, printing the reminders//
void bin(unsigned short nub)
{
if (nub <=1)
{
cout << nub;
return;
}
unsigned short rem;
rem = nub % 2;
bin( nub / 2);
cout << rem;
}
int main()
{
unsigned short dd;
unsigned short bigNumber = pow(2,sizeof(unsigned short)*8)-1;
cout << "\nPlease enter an unsigned short int between 0 and " << bigNumber << ": ";
cin >> dd;
//Should be printed if user imputs a number larger than the data type//
if ( dd > bigNumber )
{
cout << "\nThe number is invalid. Please try again.\n\n";
}
//Should be printed if user imputs a negative number//
else if (dd < 0)
{
cout << "\nThe number is invalid. Please try again.\n\n";
}
//Prints the binary number//
else
{
cout << "\nThe Binary version of " << dd << " is ";
bin(dd);
cout << endl << endl;
}
return 0;
}