Home > Blockchain >  whats wrong with this code it just give Enter an Alphabet= j ERROR! (Enter one Alphabet only not two
whats wrong with this code it just give Enter an Alphabet= j ERROR! (Enter one Alphabet only not two

Time:02-04

#include <stdio.h>
int main(void)
{
char a;
printf("Enter an Alphabet=\n");
scanf("%c",&a);
if(a>=0)
{
    printf("ERROR!\n(Enter one Alphabet only not two Alphabet or a number)");
}
else
{
    switch (a)
{
    case 'a' :
    printf("It is vowel");
    break;
    case 'e' :
    printf("It is vowel");
    break;
    case 'i' :
    printf("It is vowel");
    break;
    case 'o' :
    printf("It is vowel");
    break;
    case 'u' :
    printf("It is vowel");
    break;
    default :
        printf("it is a constant");
}
}
return 0;
} 

this code just give this result

Enter an Alphabet=
r
ERROR!
(Enter one Alphabet only not two Alphabet or a number)
--------------------------------
Process exited after 2.259 seconds with return value 0
Press any key to continue . . .

CodePudding user response:

To check if a character is an alphabetical character, you should use the isalpha function.

Putting together my other pointer (checking what scanf returns as well as using tolower, the code could be written something like this:

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char a;

    printf("Enter an alphabetical character: ");
    if (scanf(" %c", &a) != 1)
    {
        printf("Error reading input\n");
        return 1;
    }

    if (!isalpha(a))
    {
        printf("Character is not an alphabetical character\n");
        return 1;
    }

    switch (tolower(a))
    {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        printf("It's a vowel\n");
        break;

    default:
        printf("It's a consonant\n");
        break;
    }
}

[Note that the above code is still written in plain C, not C ]

  •  Tags:  
  • Related