I want this code to call generic catch block whenever any special character(eg. !,@,#,$,%,&,*, etc) is enetered in numerator or denominator. So what code should I add to this.
Any help would be appreciated. Thanks.

#include <iostream>

using namespace std;

int main()
{
    try                                                // generic catch block
    {  
       int num, den;
       double division;
       try
       {
         cout << "\n enter numerator(+ve no. only): ";
         cin >> num ;
         if (num<0) throw 3.2 ;
       }    
    
       catch(double m)
       {
          cout << "\n ERROR: numerator should be positive ";
          num = -num ;
          cout << "\n\n So your new numerator is: " << num;
       }         
    
       try
       {
          cout << "\n\n enter denominator: ";
          cin >> den ;
          if (den==0) throw 1;
       }
    
       catch(int n)
       {
          cout << "\n ERROR: You can't divide a no. by zero, enter another no: ";
          cin >> den;
       }

       division = double(num)/den;
       cout << "\n result is: " << division << "\n\n ";
    }
    
    catch(...)                              // Generic catch block
    {
       cout << "/n/n Unexpected Error: Contact your software provider";
    }  
    system("PAUSE");
    return EXIT_SUCCESS;
}

Recommended Answers

All 3 Replies

Are you saying you only want to allow numeric values and ignore all others?

Are you saying you only want to allow numeric values and ignore all others?

Yes, exactly that.

Have you looked at these?:
http://www.daniweb.com/software-development/cpp/threads/279409
http://www.devhardware.com/forums/programming-82/code-for-allowing-only-integers-in-c-31551.html

Using the example at the second link:

#include <iostream>
using namespace std;

int main(void)
{
   int intNumerator=0;
   int intDenominator=0;

   cout << "Enter the Numerator: ";
   while(!(cin >> intNumerator))
   {
      cin.clear(); // When cin fails, clear the failed flag.
      while(cin.get() != '\n'){} // This line is basically a loop the cleans out anything that is left over in the input stream.
      cout << "Try Again: ";
   }

   cout << "Enter the Denominator: ";
   while(!(cin >> intDenominator))
   {
      cin.clear();
      while(cin.get() != '\n'){}
      cout << "Try Again: ";
   }

   return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.