#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
typedef enum boolean {BFALSE, BTRUE} bool_t;
void die (char *msg)
/* This method takes a char array (string) as parameter and prints this as error message on failure, then exits */
{
fprintf (stderr, "%s\n", msg);
exit (EXIT_FAILURE);
}
bool_t get_int (int *ival)
{
char buff[5];
long lval;
char *end;
if (fgets (buff, sizeof buff, stdin) == NULL)
return BFALSE;
lval = strtol (buff, &end, 10);
if (lval < INT_MIN || INT_MAX < lval || end == buff)
return BFALSE;
*ival = (int)lval;
return BTRUE;
}
int main (int argc, const char * argv[]) {
int ranNum = 0, userGuess =0;
// generate ranNum (based on time)
srand(time (NULL));
ranNum = (rand() % 100);
printf("I have just generated a random number between 0 and 100. Can you guess it?\n\n");
while (ranNum != userGuess) {
// Validate input - if not a number between 0 and 100 then exit
if (get_int (&userGuess) != BFALSE && userGuess <= 100 && userGuess >= 0)
printf ("Your number was: %d\n", userGuess);
else {
die ("Invalid integer");
}
if (userGuess > ranNum) {
printf("Wrong! Too high!\n");
printf("Guess again:");
}
else if (userGuess < ranNum) {
printf("Wrong! Too low!\n");
printf("Guess again:");
}
}
//If all conditions met so far, numbers must match so print success and exit
printf("Well done! You guessed it! (Eventually...)\n");
return 0;
}
/* End of main.c */
I just wanted to know if you guys think this is the safest way of validating user input like this? It seems an awful convoluted way of doing it as it uses two additional functions just to safely check if input is an integer... but I've heard terrible things about scanf and obviously gets is a no-go. Any opinions?
Also, I wanted to have the game continue to loop after informing the user of the invalid input... though I can't see any way of doing this that won't make the code much more complicated. If anyone has any ideas on how to improve I'd really appreciate it. (I realise this is probably not the best way to generate a random number, I just used it so it generated something. Sure there are much better ways but meh, this works as well.)
Thanks
ZipOn


Sign In
Create Account


Back to top









