2

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

1

2 Answers 2

12

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

0
9

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

1
  • 2
    No need to explicitly compare if it returns something other than zero. Just check it the return in "truthy". Jan 17, 2014 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.