Question

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;
       }
}
Was it helpful?

Solution

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]);
    }
}

OTHER TIPS

Change your scanf ("%d"...) with scanf ("%c"...) and the definition of num from int to char. You may also change the variable name, as isalpha() and isdigit() don't work with "numbers" but with "ASCII codes of characters" (which are indeed numbers), and the prompt message from "Enter a number" to "Enter a character"

You should pass the number character by character to isdigit. Replace %d specifier by %c in scanf. And also remove the line

fflush(stdin);  

it may invokes undefined behavior (if you are not on MS-DOS).

You want to check a character not number. 0 and '0' are not the same. The first one is integer, second one is character. Change on this:

  char character =0;
  int check = 0;

  printf("Enter a number: ");

  scanf("%c", &character);
  printf("%d\n",character);

  check = isdigit(character);
  if(check != 0) {
       printf("Something something\n");
       return 0;
  }
  else{
       return 0;
  }

In action:

Enter a number: 5
53 # ASCII code of 5
2048
Something something

Enter a number: a
97 #ASCII code if a
0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top