• C

Loop till input is correct

Here is my code that i have so far. It does what it is supposed to do when a value is out of range but i want to put a loop in the main to ask to reinput the values if wrong and i cant figure this out.

#include <iostream>
#include <windows.h>



using namespace std;

class subRange
{
      public:
            subRange( int, int );
            int getValue( );

      private:
            int lower, upper;
            exception newException;
};
      
subRange::subRange( int low, int high )
{
      lower = low;
      upper = high;
}
      
int subRange::getValue()
{

      int v;
      cout << "Enter value [ " << lower << ", " << upper << " ]: ";
      cin >> v;
      
      
      if (v  < lower || v >  upper )
            throw newException;
      
      return v;
}
      
int main()
{
      subRange x(1,10);

      try {
      cout << x.getValue( ) << endl;
      cout << "You have entered a Valid value" << endl;
      
      }
      catch (exception e)
      {
            cout << "Value out of Range" << endl;
      }
      Sleep (5000);
}
chetmunk700Asked:
Who is Participating?
 
phoffricCommented:
My book says: "Exception handling is a less structured mechanism than local control structures such as if and for and is often less efficient when an exception is actually thrown. Therefore, exceptions should be used only where the the more traditional control structures are inelegant or impossible to use."

So evilrix's solution avoids exceptions altogether replacing with the usual control structures.

But if you are primarily interested in learning how to use exceptions, then below is an example to accomplish your goal. First, to make the exception handling more informative, the function throws the actual bad value which the main exception handler than prints out informing the user of exactly what went wrong.
int subRange::getValue()
{

    int v;
    cout << "Enter value [ " << lower << ", " << upper << " ]: "; 
    cin >> v;

    if (v  < lower || v >  upper )
        throw v;                  // <--- throw some useful feedback information

    return v;
}

int main()
{
    const int low = 1, high = 10;
    bool good_input = false;
    subRange x(low, high);

    while( ! good_input ) { // <--- Shows a clear reason for continuing with the loop
        try {
            cout << x.getValue( ) << endl;
            cout << "You have entered a Valid value" << endl;
            good_input = true;  // <-- Now have a good input, so say so to get out of loop
        }
        catch (int badValue)
        {   // <--  catch the exception and provide useful information
            cout << badValue << " is out of Range [" << low << ".." << high << "]" << endl;
        }
    }
}

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
A couple of observations:

1. I wouldn't use exceptions for controlling if the user entered an invalid value. It's not really an exceptional condition and it is generally considered bad practice to use exceptions for flow control purposes other than a way of handling unrecoverable or exceptional conditions.

2. Since getValue is responsible for getting the user input it would probably make more sense to put the retry loop in there (you can use an optional bool parameter to disable the retry if you liked. The reason I would do this is that it encapsulates all the behaviour in the class meaning it an be reused in other places without duplication code.

So, as for how to loop something as simple as this should do...




int subRange::getValue()
{

      int v;

      for(;;) //<--- will loop forever until the break in the if clause is executed
      {
         cout << "Enter value [ " << lower << ", " << upper << " ]: "; 
         cin >> v;
      
      
         if (v  >= lower && v <=  upper ) // <--- note the logic here is inverted from your original test
              break; // <--- This will terminate the loop
      }

      return v;
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.