Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.");
        

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading