Number guesser
This is a simple guessing game. The computer picks a random number, and the user has to guess what it is in as few goes as possible.
By default, the computer picks a number between 1 and 100, but the user can specify a different maximum number by specifying it as the command line (see usage below).
Programming Issues
The following issues are involved:
- Choosing a random number. The statement
rand() % num + 1;
will pick a random number between 1 and n. Note the call tosrand()
near the beginning; this is necessary or the computer will pick the same set of "random" numbers every time the program is run. - Getting input from the user. A simpler way would be to call
scanf()
which would work fine, providing the user entered numbers when they should. If the user enters something else (e.g. a character) then a "matching failure" occurs.scanf()
is notoriously bad at coping with matching failures, so we implement a different method:- Call
fgets()
to retrieve an entire string from stdin - Call
sscanf()
on that string to retrieve the number
- Call
- Retrieving the maximum number the user specifies from the command line. The program simply checks whether the user entered one argument, and if they did, it tries to convert it to a valid number.
Usage
Run the program by typing:
guesser
for a number between 1 and 100. To specify a different maximum number, use:
guesser 20
where the computer will pick a number between 1 and 20 (or whatever number you specify).