[prog] validate input

Jacinta Richardson jarich at perltraining.com.au
Mon Dec 22 14:56:15 EST 2003


On Sun, 21 Dec 2003, wolf wrote:

> However, how
> would I have it check if the user correctly entered a 1 or a 2 and if 
> they did not tell them "Invalid Entry Try Again".

There is a rather easy modification to your script to make this work.
All you have to do is tell the while loop to go back to the start and
try again when you get an answer you don't like.

There are two ways to change the execution of a while loop:
	continue - go back to the top of the loop, re-evaluate the
		   conditional, and proceed as  normal
	break	- break out of the while loop, even if the condition
		  is still true and proceed from the first line under
		  the while loop.

Hopefully it's obvious that you'll be wanting to use "continue" in this
case.
Suggested code, with comments below.

----------------------------------------------------
// (Each program should have a description at the top of what it does etc)
/* pass_fail.cc
*  This program processes the results for 10 students and if 8 or more
*  have passed suggested tuition should be raised.
*
*  Author: wolf <wolf at wolfrising.net>
*  Date:   December 2003
*
*  Edited: Jacinta <jarich at perltraining.com.au>
*/

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

#define STUDENTS 10		// This gives us a single place to change
				// the number of students we're processing
#define TUITION_RATE 8		// If more than this number of students
				// pass we should raise tuition.

int main()
{
        int passes = 0;
        int failures = 0;

        int result;
        int studentCounter =1;

        cout << "Processing results for " << STUDENTS << " students." << endl;
        while ( studentCounter <= STUDENTS ) {

                cout << "Enter result for student number " << studentCounter
                        << ". (1 = pass, 2 = fail): ";
                cin >> result;

                if ( result == 1) {
                        passes++;
                }
                else if (result == 2) {
                        failures++;
                }
                else {
                        // invalid input
                        cout << "Please enter either 1 or 2." << endl;
                        continue;	// (restarts loop from top)
                }
                studentCounter++;
        }

        cout << "Passed " << passes << endl;
        cout << "Failed " << failures << endl;
        if (passes >= TUITION_RATE) {
                cout << "Raise Tuition " << endl;
        }

        return 0;
}

----------------------------------------------------

You'll notice that I've made a number of changes to your code.  Instead
of:
	passes = passes + 1;
I've changed it to the shorter-hand:
	passes++;
which does exactly the same thing.

I've put {}s around all of your if blocks and such (which you can
ignore, I'm just too used to Perl) and I've added a few more things to
what you print out.  I've also gotten rid of large sections of white
space because I think that they make the script look wierd.

I think it's important to give the user feedback on which element
they're processing.  If I had a list of students and I was entering
results, it'd be nice to be told which student I was up to, just in case
I lost count or was interrupted for some reason.  This also shows that
the student number we're processing does not change when we make a
mistake.

I've changed the original else block to an else if, to check that we're
only accepting 2 to mean a failure and added an else block to catch any
other input.  This block prints an error and restarts the loop from the
top.  Note that continue works nicely in this case because we don't
increment studentCounter until AFTER we've processed the input.  This
means that even if the final input is in error, we'll still restart the
loop because student number 10 is still less than or equal to 10.  When
you use continue you must make sure that your conditional will still
evaluate correctly for the situation.

I've added in some hash defines to allow us to easily change the number
of students or the tutition rate without having to read over the whole
script.  Your 10 and 8 in this case would commonly be called "magic
numbers" and as you program more you'll discover that magic numbers are
rather bad things to scatter through your code.

I hope this helps,

          Jacinta
--
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +613 9354 6001         |  
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
(il),-''  (li),'  ((!.-'              |   www.perltraining.com.au   |




More information about the Programming mailing list