I have no idea why isdigit()
and isalpha()
keep doing this. No matter how I use them they always return a 0
. Am I using them incorrectly or is my compiler acting up?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
//example of isdigit not working, it ALWAYS returns 0 no matter what the input is.
int main()
{
int num=0;
int check=0;
printf("Enter a number: ");
fflush(stdin);
scanf("%d",&num);
//Just checking what value isdigit has returned
check=isdigit(num);
printf("%d\n",check);
if(check!=0)
{
printf("Something something");
system("pause");
return 0;
}
else
{
system("pause");
return 0;
}
}
isdigit
acts on an int, but it is supposed to be char extended to an int. You are reading a number and convert it to a binary representation, so unless your inout happens to be a value matching0
- ´9` (i.e. 0x30 - 0x39) you will get false as a result.If you want to use
isdigit()
you must use it on the individual characters from the string the user enters as the number, so you should use%s
, or%c
for single digits, and loop through the string.Example:
or (quick and dirty example)