[prog] validate input

James Sutherland jas at spamcop.net
Mon Dec 22 03:17:56 EST 2003


On Sun, 21 Dec 2003 20:23:40 -0500, wolf <wolf at wolfrising.net> wrote:

> Hi, I have this C ++ code that basically adds up out of 10 students who 
> passed and who did not. You enter 1 if the student passed
> and 2 if the student failed.  It loops around so you can enter your 
> answer 10 times. All fine and good : ) 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".  The code
> as is, does seem to work correctly : ) I'm working on sample practice 
> questions and very much a beginner. Also, if there's
> a way to improve the comments, or if the indentation is incorrect, 
> please feel free to point that out as well.  I'd like to break
> any bad habits at the beginning.  Thanks : )


Try a code segment like this:


result=0;
while(result!=1 && result!=2)
{
	cout << "...";
	cin >> result;
	if (result==1)
		passes++;
	else if (result==2)
		fails++;
	else
		cout << "Bad user! Try again...";
}


Two alternatives:

Adjust the problem slightly: instead of using 1 and 2, use 1 and "anything
else". That way, there are no invalid answers!

Or count the 10 entries: set a counter to 10, and decrement it for each
valid answer. That doesn't give the immediate feedback, but does ensure
the user enters 10 valid entries.


James.


More information about the Programming mailing list