• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 222
  • Last Modified:

Having trouble adding exception handling code to function that contains a do while loop

I need to add exception handling code to a function for entries that are not integers.  I am having trouble because the file contains a do while loop.

Here is the function:
int instructions( void )
{
   int choice;
   // ask user to enter a choice
   cout << "\nEnter a choice:\n" <<
                  "1  List all records.\n" <<
                  "2  Change record.\n" <<
                  "3  Add a record.\n" <<
                  "4  Delete a record.\n" <<
                  "5  Quit.\n";
   // ask user for choice until a valid choice is entered
      do {
            cout << "? ";
            cin >> choice;
           } while ( choice < 1 || choice > 5 );
    return choice; // return user choice
} // end function instructions

I tried this- but got caught in an infinite output loop-
int instructions( void )
{
   int choice;
   // ask user to enter a choice
   cout << "\nEnter a choice:\n" <<
                  "1  List all records.\n" <<
                  "2  Change record.\n" <<
                  "3  Add a record.\n" <<
                  "4  Delete a record.\n" <<
                  "5  Quit.\n";
   // ask user for choice until a valid choice is entered
try   {
         if (!(isdigit(choice))) throw exception();
         else
           do {
          cout << "? ";
          cin >> choice;
      } while ( choice < 1 || choice > 5 );
   }
   catch (...)  {
         cerr << "\nException error: Invalid Entry!\n";
   }    return choice; // return user choice
} // end function instructions
0
coririzzo
Asked:
coririzzo
  • 3
  • 2
  • 2
1 Solution
 
jkrCommented:
We already did that in http:Q_21223482.html - the idea was to

#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;

bool read_integer ( istream& is, int& i) {

   int n;
   string str;
   char* pcCnvEnd = NULL;

   getline(is,str); // read input

   n = (int) strtol(str.c_str(),&pcCnvEnd,10); // try to convert the string to int

   if ( *pcCnvEnd) // conversion did not end at the term. NULL -> invalid input
     return false;

   i = n; // conversion successful, was an int

   return true;
}

int instructions( void )
{
 int choice;

 // ask user to enter a choice
 cout << "\nEnter a choice:\n" <<
             "1  List all records.\n" <<
             "2  Change record.\n" <<
             "3  Add a record.\n" <<
             "4  Delete a record.\n" <<
             "5  Quit.\n";

 // ask user for choice until a valid choice is entered
 do {

   if ( !read_int(cin,choice)) continue; // go on in the loop if input was invalid

  } while ( choice < 1 || choice > 5 );

 return choice; // return user choice

} // end function instructions
0
 
udo_borkowskiCommented:
I would suggest that you rewrite your routine like this, since Exceptions should only be used of "exceptional situation" (and a wrong user input is not exceptional). Also you should not use exceptions for "control flow" purposes.

here my suggestion:

int instructions( void )
{
    char choice;
      do {

       // ask user to enter a choice
       cout << "\nEnter a choice:\n" <<
               "1  List all records.\n" <<
               "2  Change record.\n" <<
               "3  Add a record.\n" <<
               "4  Delete a record.\n" <<
               "5  Quit.\n";

       cout << "? ";
       cin >> choice;
       if (!(isdigit(choice))) {
            cerr << "\nException error: Invalid Entry!\n";
       }
   } while ( choice < '1' || choice > '5' );
   return (choice -'1')+1;
}


(BTW: the choice value in your code was not initialized)
0
 
coririzzoAuthor Commented:
Thanks jkr- your previous answer was great, but I wanted to try it with exception handling code.
udo_borkowski - I tried your solution, and am still getting an infinite output loop.  I think it may be due to this code from main:  

 while ( ( choice = instructions( ) ) != 5 ) {
            switch (choice){
            case 1:      listEMailObjs(file );
                  break;
            case 2:      updateRecord(file );
                  break;
            case 3:      insertRecord(file );
                  break;
            case 4:      deleteRecord(file);
                  break;
            default:      cout<< "Error";
                  break;
         }
      file.clear();    // reset eof indicator
   } // end while

One more dumb question- I am rather new here, and I don't know how to make my response show up as an "author comment".  
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
jkrCommented:
>>but I wanted to try it with exception handling code

OK, if it is about practising that I agree. You could e.g. try

#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;

enum InputError {

   NotAnInteger,
   SomethingUnknown
};

void read_integer ( istream& is, int& i) {

  int n;
  string str;
  char* pcCnvEnd = NULL;

  getline(is,str); // read input

  n = (int) strtol(str.c_str(),&pcCnvEnd,10); // try to convert the string to int

  if ( *pcCnvEnd) // conversion did not end at the term. NULL -> invalid input
    throw NotAnInteger;

  i = n; // conversion successful, was an int
}

int instructions( void )
{
int choice;

// ask user to enter a choice
cout << "\nEnter a choice:\n" <<
            "1  List all records.\n" <<
            "2  Change record.\n" <<
            "3  Add a record.\n" <<
            "4  Delete a record.\n" <<
            "5  Quit.\n";

// ask user for choice until a valid choice is entered
do {

  try {

    read_int(cin,choice);

  }
  catch ( InputError e) {

     if ( NotAnInteger == e) cout << "NotAnInteger\n";
       else cout << "Something unknown went wrong\n";

     continue;
  }

 } while ( choice < 1 || choice > 5 );

return choice; // return user choice

} // end function instructions
0
 
udo_borkowskiCommented:
> One more dumb question- I am rather new here, and I don't know how to make my response show up as an "author comment".  

Your comments appear as "author comment" to us (you will probably just see "Your comment")

0
 
udo_borkowskiCommented:
> udo_borkowski - I tried your solution, and am still getting an infinite output loop.  I think it may be due to this code from main:  ...

And this infinite output loop does not occur with jkr's solution?

And what exactly is written to the output?

Do I need to know what file you are "clearing" at the end of your case block?
0
 
coririzzoAuthor Commented:
Thanks jkr- that works!  I was wrong about the switch causing the problem.
Udo- you were right- I do see it as "your comment"- DUH
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now