Lab 3 - Input Validation and Menus

Part 1

Program Requirements:

Work in your own Odin directory 2010/3/
Name this program guess.cpp

Input validation...

Ask the user to pick a number from 1 to 10.

Read the number into an integer.
Use a compound boolean expression for validation.
If the number is out of range, print an error message and exit the program. If in range, show the number entered on the screen.

Run the program multiple times to make sure you are validating the input correctly. Try entering a negative number, then try 0, then try 1, then try 10, then try 11, and so on. Testing 0, 1, 10, and 11 is called boundary testing to make sure the program behaves correctly when the input switches from bad to good and vise versa.

Running your program will look something like this...


Number guessing game.

Enter a number from 1 to 10: 6

Your number was 6, but the secret number was 3.
Sorry, you lose.


Turn your program into a game...

Start a new program named: game.cpp

Have your program generate a "secret number" that you do not even know.

Here's what to do:
Seed the random number generator: srand(time(NULL));
Generate a random number from 1 to 10.
Store it in an integer.
Compare the user's input to this number.
Display "winner" or "loser" based on the result.

Here's how to do it:
Use the rand() function to get a random number.
Use the modulus operator to control the range.
Example: rand() % 2 produces an integer between 0 and 1.
Example: rand() % 100 produces an integer between 0 and 99.
Example: rand() % 100 + 1 produces an integer between 1 and 100.

Add this statement: #include <cstdlib> near the top of your program.
You may refer to Google or textbook for help with the rand() function.

Your program will look like this...


Number guessing game.

Enter a number from 1 to 100: 60

Your guess is low. Try again: 85

Your guess is high. Try again: 81

Winner!!!
It took you 3 tries.

Gordon will show you how to get input in a loop.

Part 2

Program Requirements:

Setup a menu to get user input.

Work in Odin directory 2010/3/
Name this program menu.cpp

Your program will display a menu such as below.


lab3 menu
--------------------------------------
1. calculate area of a rectangle
2. calculate area of a triangle
3. calculate surface area of a sphere
0. Quit
--------------------------------------
Enter your selection:

Prompt the user for the appropriate values needed to calculate the areas.
Produce some nice neat output.

Get user input and calculate the results with 3 decimal places of precision.
use setprecision() and fixed.
Setup a named constant to hold the value of Pi.

Validate user input:
1. no negative values allowed.
2. values above 1000.0 are not allowed.

Gordon will demonstrate how to make this menu run over and over until the user decides to exit by entering 0.

What to turn in...

Your instructor will find your programs on Odin.
   2010/3/guess.cpp
   2010/3/menu.cpp

Programs will be collected at lab end.