// L-6 MCS 360 Fri 3 Sep 2010 : in_char_range.cpp

/* The user is prompted for an integer number
   and the program attempts to convert to a character.

   If the number is in the range 0..255, 
   then the corresponding character is written to screen.
   Otherwise, the exception bad_cast is first thrown
   and then caught and an error message is written. */

#include <iostream>

using namespace std;

char to_char ( int n );
// converts n to a character
// throws bad_cast exception if n < 0 or n > 255

bool int2char ( int n, char& c );
// converts n to a character c
// returns true if okay, false otherwise

int main()
{
   int n;

   cout << "Give an integer : ";
   cin >> n;

   char c;
   bool okay = int2char(n,c);

   if(okay)
      cout << "The integer " << n 
           << " corresponds to character \'"
           << c << "\'." << endl;
   else
      cout << "Cannot convert " << n 
           << " to a character." << endl;

   return 0;
}

char to_char ( int n )
{
   if((n < 0) || (n > 255))
   {
      cerr << "Throwing bad_cast exception ...";
      throw(bad_cast());
   }
   return char(n);
}

bool int2char ( int n, char& c )
{
   try
   {
      c = to_char(n);
      return true;
   }
   catch(bad_cast)
   {
      cerr << " caught bad_cast exception." << endl;
      return false;
   }
}

