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

Andrea
  • 6,032
  • 2
  • 28
  • 55
Computernerd
  • 7,378
  • 18
  • 66
  • 95
  • 3
    Comparing with `true` is an antipattern (at least in C and C++). See http://stackoverflow.com/questions/356217/should-i-use-isgood-or-isgood-false/356709#356709 – Michael Burr Jan 17 '14 at 10:03

2 Answers2

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

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
9

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

Andrea
  • 6,032
  • 2
  • 28
  • 55