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 matching 0
- ´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:
char c;
scanf("%c",&c);
check=isdigit(c);
or (quick and dirty example)
char buffer[200];
if (scanf("%s", buffer) > 1)
{
int i;
for(i = 0; buffer[i] != 0; i++)
{
check=isdigit(buffer[i]);
}
}