-
isdigit issue - help
Challenge 2: 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).
Unable to get this program to work. I've tried everything.
Code:
//Chapter 3 Challenge 2
//by Lori Macdonald
#include <stdio.h>
#include <ctype.h>
main()
{
int iRandomNum = 0;
int iResponse = 0;
srand(time());
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 and 10: ");
scanf("%d", &iResponse);
getch();
switch (iResponse) {
case 1:
if (isdigit(iResponse))
printf("\nThank you\n");
else {
printf("\nYou did not enter a digit\n");
}
case 2:
if (iResponse == iRandomNum)
printf("\nYou guessed right\n");
else {
printf("\nSorry, you guessed wrong\n");
printf("The correct guess was %d\n", iRandomNum);
}}
getch();
}
Lori
-
And what, pray tell, do you think "switch" does?
(Oh: and you'll never be able to get a letter input via scanf("%d"). Since the parameters of the assignment require that you (sort-of) accept letter input, you cannot use scanf("%d").)
And as to the question: isdigit requires a character, not an integer.
-
And someone's gonna crash without "brakes"...
-
And the input for isdigit is a character (although the type is technically int, that is so that you can safely feed EOF into isdigit, and it will be different from char number 255). It will NOT tell you if the user entered something that is a valid number - it will tell you if the input is between 48 (ascii code for '0') and 57 (ascii code for '9') [and possibly some other numbers in foreign, typically Asian, fonts if you use wide characters]. Of course, due to your use of switch, it will only hit the isdigit if the number is 1, which is not in the range 48..57, so it's always going to be "not a digit".
--
Mats