Reputation: 37
The result from my program is not what I expect and it is different on different compilers.
I have tried it on three compilers, two of which give the same result. But I want a combination of the two results.
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int iRandomNum = 0;
int iUserInput = 0;
const int VIP = 7;
srand(time(NULL));
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 to 10.\n Make a wish and type in the number.\n");
scanf("%d", &iUserInput);
if(isdigit(iUserInput))
{
printf("\n\nYou did not enter a digit between 1 to 10.\n\n");
}
else
{
if(iUserInput==iRandomNum || iUserInput==VIP)
printf("\n\nYou guessed it right!\n\n\n");
else
printf("\n\nSorry the right answer was %d.\n\n\n", iRandomNum);
}
return 0;
}
When I choose any number, the program should only alert me if I have not chosen the correct number in this number guessing game. But in the case of 7, we always have the right answer. This happens in the two online compilers. But in clang, when I do this & does not work. The isdigit function does not work then
Upvotes: 1
Views: 94
Reputation: 16876
Using the %d
format specifier, you're reading an int
into iUserInput
. That's correct, but then you use isdigit
to try to see whether the number is between 1
and 10
. However, this function is for finding out whether a char
is between '0'
and '9'
. That's not the same - assuming ASCII those chars are equal to to 48
and 57
respectively. So You isdigit
check most likely finds out whether the inputted number is between 48
and 57
(although there's no guarantee that ASCII is used, so a different encoding might lead to different results).
Instead, the check should be:
if((iUserInput >= 1) && (iUserInput <= 10)) {...}
Upvotes: 3