isalpha() function returns false for character in string

11,031

Solution 1

The return type of isalpha is int, not bool (it comes from C). It returns 0 when the check fails, and a nonzero value when it succeeds. Note that it does not have to return 1 in such case.

Comparing an int to true promotes the true to the integer 1. Then the comparison fails for integers other than 1.

You should never check logic values by comparing with true or false - rely on the value or implicit conversion instead:

if ( isalpha(foo[i]) )
{
  count++;
}

Live example

Solution 2

isalpha() returns an int. You should check if it returns a value different from 0.

Share:
11,031
Computernerd
Author by

Computernerd

I like to ask questions

Updated on June 05, 2022

Comments

  • Computernerd
    Computernerd almost 2 years

    I am trying to count the number of letters in a string by checking for every character in the string fooby using the pre-defined function isalpha()

    #include <iostream>
    #include <string>
    #include <cstdlib>
    
    using namespace std;
    
    
    int main()
    {
        string foo = "aaaaaaa1";
    
        int count=0;
    
        for (int i=0;i<foo.length();i++)
        {
            if ( isalpha(foo[i]) == true)
            {
                count++;
            }
        }
    
        cout<<count;
    
        system("PAUSE");
    }
    

    Expected output :

    7

    Current output :

    0

    The error is that function isalpha is not returning true for alphabetic ,

    Can someone explain to me why and how to solve the problem to check if a given character is a alphabetic