guesser.c


/*

  GUESSER.C
  =========
  (c) Paul Griffiths 1999
  Email: mail@paulgriffiths.net

  Simple number guessing game

*/


#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>


/*  Global macro  */

#define BUFFER_SIZE             (100)


/*  Forward function declarations  */

void ParseCmdLine(int argc, char *argv[], int *max);


/*  main() function  */

int main(int argc, char *argv[]) {
    int guess, target, goes = 0, max = 100;
    char buffer[BUFFER_SIZE];

    /*  Get maximum number from command line  */

    ParseCmdLine(argc, argv, &max);


    /*  Seed random number generator  */

    srand( (unsigned) time(NULL) );
    

    /*  Output welcome message  */

    printf("Number Guesser\n");
    printf("==============\n\n");


    /*  Loop until user wants to quit  */

    do {
	printf("I'm thinking of a number between 1 and %d.\n", max);
	printf("Can you guess what it is?\n\n");


	/*  Pick a random number to guess  */

	target = rand() % max + 1;
    

	/*  Loop until correct answer  */
    
	do {

	    /*  Get a guess from the user  */

	    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);
	    }
	    
	    
	    /*  Test whether user guessed the right number  */
	    
	    if ( guess < target )
		printf("Too low! ");
	    else if ( guess > target )
		printf("Too high! ");
	    ++goes;

	} while ( guess != target );
	
	
	/*  User has guessed the right number  */
	
	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;
}


/*  Gets maximum number from command line  */

void ParseCmdLine(int argc, char *argv[], int *max) {
    char *endptr = NULL;

    if ( argc == 2 ) {

	/*  Convert first command line argument
	    to a number and store it in 'max'    */

	*max = strtol(argv[1], &endptr, 0);

	if ( *endptr ) {

	    /*  Command line argument was not numeric  */

	    printf("You did not enter a valid maximum number.\n");
	    exit(EXIT_FAILURE);
	}
	else if ( *max < 2 ) {

	    /*  No point guessing a number between 1 and 1  */

	    printf("Maximum number must be at least two!\n");
	    exit(EXIT_FAILURE);
	}
    }
}



Please send all comments, suggestions, bug reports etc to mail@paulgriffiths.net