ccharactergetcharisalpha

C Program to count number of alphabets in a word giving error


Following is the code:

#include<stdio.h>

int main()
{
    int alpha = 0, input;

    while((input = getchar() != EOF))
    {
        if(isalpha(input))
            alpha++;
    }

    printf("Num of alpha is %d", alpha);
    return(0);
}

I'm getting error as

isalpha was not declared in this scope

when compiled on DevC++ compiler.


Solution

  • isalpha() is declared in ctype.h

    It might be good to know that even though the argument to isalpha (and all the isxxx family functions) is an int, the behavior is undefined if the argument is negative. So if you're on a machine where char is signed as default, you might run into trouble unless you cast first. Like this:

    char c;
    // Some code
    if(isalpha((unsigned char) c)) {
    

    It can be a good habit to always cast for these functions. However, do NOT use casting as a goto for silencing warnings. It can easily hide errors. In most cases when a cast is needed, your code is wrong in some other way. Rant about casting

    Another pitfall with these functions (and many other C functions that returns an int as a Boolean) is that they are required to return zero on false, but are allowed to return any non-zero value on true. So a check like this is complete nonsense:

    if( isalpha(c) == 1 ) 
    

    Instead do any of these:

    if( isalpha(c) != 0 )   // If not zero
    if( isalpha(c) )        // Use directly as Boolean (recommended)
    if( !! isalpha(c) == 1) // Double negation turns non zero to 1