Home > Blockchain >  Odd and even in c with error if input is letters or special character
Odd and even in c with error if input is letters or special character

Time:10-06

This is my sample code but it is limited on 0-9 number only i want it to check the number to 0 to 9999 can someone help me i use ascii because the special character wont work if i dont use ascii code and i think thats why the number it check is limited on 0 to 9

#include<stdio.h>

int main()
{
char a;
printf("Enter anything here: ");
scanf("%c", &a);
 
if (a >=65 && a <=90)
printf("%c is an Uppercase Alphabet.", a);

else if (a >=97 && a <=122)
printf("%c is a Lowercase Alphabet.", a);

else if((a >=48 && a <=57) && (a % 2 == 0))
printf("%c is an Even Number", a);

else if((a >=48 && a <=57) && (a % 2 != 0))
printf("%c is an Odd Number", a);

else if ((a >=0 && a <=47)||(a >=58 && a <=64)||(a >=91 && a <= 96)||(a >= 123))
printf("Special Symbol.");
        

}

CodePudding user response:

When you scanf with %c you request is single character. If you want to request a string, you should rather want to use %s:

#define MAX_LEN  4
char string[MAX_LEN   1]; // NULL terminated
scanf("%4s", string);

In the example above, you read a string of 4 characters at most (i.e.: the maximal length of you buffer excluding the NULL termination character.

Then, to ensure it is only made of digit you can run your algorithm within a for-loop to check each character one by one:

size_t len = strlen(string);
size_t i;
for (i = 0; i < len; i  ) {
    // TODO: check ASCII value
}

This works..

NOTE: the latter assumes you want to get a number from N characters given by the user.

.. BUT ! There are alternatives to this later check. For instance, you can use strtol which can tell you whether or not the passed input was a well formatted number:

int number;
char *p;

/* string is the string to convert to number.
 * &p is a pointer where to store the last character the function stopped.
 * 10 is the base to use. */
number = strol(string, &p, 10);

if (*p != '\0') {
    /* The input was most likely not just a number [0-9]. */
    // TODO: you can check here to know whether it was a special
    //  char, a letter, etc.
}

CodePudding user response:

c is character feild so it can't take integer value. it can only use for integers

  •  Tags:  
  • c
  • Related