guesser.c
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#define BUFFER_SIZE (100)
void ParseCmdLine(int argc, char *argv[], int *max);
int main(int argc, char *argv[]) {
int guess, target, goes = 0, max = 100;
char buffer[BUFFER_SIZE];
ParseCmdLine(argc, argv, &max);
srand( (unsigned) time(NULL) );
printf("Number Guesser\n");
printf("==============\n\n");
do {
printf("I'm thinking of a number between 1 and %d.\n", max);
printf("Can you guess what it is?\n\n");
target = rand() % max + 1;
do {
printf("Enter your guess: ");
fgets(buffer, BUFFER_SIZE - 1, stdin);
while ( !sscanf(buffer, "%d", &guess) ) {
printf("Enter a number! ");
fgets(buffer, BUFFER_SIZE - 1, stdin);
}
if ( guess < target )
printf("Too low! ");
else if ( guess > target )
printf("Too high! ");
++goes;
} while ( guess != target );
printf("Well done, it was %d!\n", target);
printf("You took %d goes.\n\n", goes);
printf("Another go? (y/n) ");
fgets(buffer, BUFFER_SIZE - 1, stdin);
} while ( buffer[0] == 'y' || buffer[0] == 'Y' );
printf("Goodbye!\n");
return EXIT_SUCCESS;
}
void ParseCmdLine(int argc, char *argv[], int *max) {
char *endptr = NULL;
if ( argc == 2 ) {
*max = strtol(argv[1], &endptr, 0);
if ( *endptr ) {
printf("You did not enter a valid maximum number.\n");
exit(EXIT_FAILURE);
}
else if ( *max < 2 ) {
printf("Maximum number must be at least two!\n");
exit(EXIT_FAILURE);
}
}
}
Please send all comments, suggestions, bug reports etc to mail@paulgriffiths.net