The task is rather simple: Prompt the user to input a value between 1 and 9. If you’ve read the first few chapters of any of my For Dummies C programming books, you could do that one easily. But what happens when the user doesn’t type a value in that range or — worse — they type text instead?
Back in the day, programmers would call the technique “bullet-proofing.” It’s the process of preventing code from running amok by planning for all possibilities.
I remember beta testers — and these were real beta testers and not merely early adopters — who would go to every prompt in a program and type any possible input to test the code.
For example, a configuration option prompted the user had to enter a value in the range of 1 to 9. One beta tester discovered that if you typed two dozen 9s that the code would crash. That is good beta testing. While it might seem ridiculous for anyone familiar with the program to do something other than what the prompt says, users aren’t obedient.
For this month’s Exercise, you need to write a simple prompt that asks for a value in the range of 1 to 9. The assumption is that the user will type in anything from a super huge value to text to nothing at all. The code must evaluate the input, confirm whether or not it’s proper, and ask for input again if the current input is invalid.
Here is a sample run of my solution, which will help you get an idea of what I’m after:
Enter a number 1 to 9: This is a test
Incorrect input. Try again:
Enter a number 1 to 9: 888888888888
Incorrect input. Try again:
Enter a number 1 to 9: 5
You input 5
Thank you!
Several methods exist for solving this puzzle. Be sure to test all kinds of whacky input to bullet-proof your code. Click here to read my solution, but I encourage you to try this Exercise on your own before seeing what I did.