[prog] validate input
Daniel.
cristofd at hevanet.com
Sun Dec 21 19:46:13 EST 2003
>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".
Other people rightly suggested an "else if" construction. This is a
very common way to make multi-way decisions, and it deserves a little
more explanation. Following the usual rules for formatting if-else
statements, it would look like this:
if (condition 1)
action 1
else
if (condition 2)
action 2
else
if (condition 3)
action 3
else
action 4 //none of the above conditions hold
When it's formatted this way, it's clear how it's built from several
nested if-else statements. Notice that exactly one of the actions
(which may be single statements, or compound statements in {} blocks)
will be done. The thing is that when you format it that way, it tends
to wander off the right side of the page if there are too many
conditions. So this particular arrangement of if-else statements is
usually formatted like this instead:
if (condition 1)
action 1
else if (condition 2)
action 2
else if (condition 3)
action 3
else
action 4 //none of the above conditions hold
(Notice, by the way, that "else" is an archaic word for "otherwise".)
You probably want to use one of these, with separate cases for "1",
"2", and "none of the above" (the final else). You'll have to make
sure that the student count gets increased only when the user gives
valid input, too.
>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 : )
Okay. The indentation is mostly fine, but it might be a good idea to
decide between these two bracket styles:
while (condition){
do things
}
while (condition)
{
do things
}
Both styles have their adherents; I tend to prefer the first because
it eats less vertical space. But in any case, I would choose one and
stick with it, instead of using a blend of both. The main problem
with the indentation is that you indented "return 0" and the final }
too far...the final } should be at the left edge, and the "return 0"
only indented one level from that, since it's in main() but not
inside anything else.
Good luck;
-Daniel.
--
() ASCII ribbon campaign () Hopeless ribbon campaign
/\ against HTML mail /\ against gratuitous bloodshed
More information about the Programming
mailing list