I've been working on this program for a good couple of weeks between my work hours.
The challenge in the book was:
Build a number guessing game that uses input validation (isdigit function) to verify that the user has entered a digit and not a non-digit (letter).
The following is the best I could come up with.
You'll notice that I ask the user to input their guess twice, once to assign to an integer and once to a character because I had no idea how to effectively convert the character to an integer.
This is the first proper game I have made with C so please feel free to point out any rookie errors :>
Any suggestions as to how to improve the code from here?
Cheers.
Code:#include <stdio.h> #include <stdlib.h> #include <ctype.h> int main() { int iRandomNum = 0; srand(time(NULL)); char cResponse = '\0'; int dResponse = 0; iRandomNum = (rand()%10)+1; printf("iRandomNum= %d\n",iRandomNum); printf("please enter a digit\n"); scanf("%c",&cResponse); printf("One more time?\n"); scanf("%d",&dResponse); printf("cResponse= %c\n",cResponse); if (isdigit (cResponse)==0) printf("letter was inserted, please enter a number next time\n"); else printf("iRandomNum= %d, this is a digit.\n",iRandomNum,", \n"); if (dResponse == iRandomNum) printf(" well done!"); else { printf("you lose\n"); printf("You guessed cResponse= %c\n",cResponse); printf("You should have guessed %d",iRandomNum);} }



1Likes
LinkBack URL
About LinkBacks



