Link to home
Start Free TrialLog in
Avatar of chetmunk700
chetmunk700

asked on

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);
}
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

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

ASKER CERTIFIED SOLUTION
Avatar of phoffric
phoffric

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial