I have this function that should count how many characters are letters in the English

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abueno
    New Member
    • May 2009
    • 16

    I have this function that should count how many characters are letters in the English

    //It should count how many characters are letters in the English alphabet, and is
    displaying the correct letters, but is not counting good.

    Code:
    void FunctionCountLetters(char s[])
    {
    int len;
    int i;
    len=strlen(s);
    cout<<"\n The lenght of the string is= "<<len<<endl;
    
    int counter=0;
    for(i=0; i<len; i++)
    {
    if((s[i]>='a'&& s[i]<='z')||(s[i]>='A'&& s[i]<='Z'))
       cout<<"The letters in the English alphabet are: "<<s[i]<<endl;
       counter++;
    
    }//end of for loop.
    
    cout<<"The number of letters in the English alphabet are: "<<counter;
    
    
    }//end of function count letters.
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    I think you need to put some braces round the body of the if statement.
    Also its much easier for people if you enclose your code in [CODE]...[/CODE]
    tags. Also if you change the string to all capitals or all lower case you can halve the length of your if statement.

    Comment

    • abueno
      New Member
      • May 2009
      • 16

      #3
      Thank you whodgson, yes I forgotten to put some braces. I got it now.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Code:
        if((s[i]>='a'&& s[i]<='z')||(s[i]>='A'&& s[i]<='Z'))
        Notice that this code assumes that the character code for 'a' is less than 'z', and that the character codes for all the lowercase letters fall between them, and that there are no other character codes in that range; and that the same holds true for 'A' and 'Z'.

        This is true for ASCII, but not for other character codes your program might encounter. For example, EBCDIC does not conform to this assumption.

        You want to do the following in order to be fully portable:
        Code:
        if(isalpha(s[i]))

        Comment

        • abueno
          New Member
          • May 2009
          • 16

          #5
          Thank you donbock, that's true....

          Comment

          Working...