hedgers
hedgers

Reputation: 49

CS50 Readability Pset2

I am having trouble getting my code to correctly count the number of letters in a string my code still counts the spaces even tho the function I called below only checks for alphabetic characters it still counts the spaces. If I type Hello World is counts 11 letters even tho only 10 letters are present

isalpha() checks for an alphabetic character; in the standard "C" locale, it is equivalent to (isupper(c) || islower(c)). In some locales, there may be additional characters for which isalpha() is true—letters which are neither uppercase nor lowercase.

Heres my code

#include <stdio.h>
#include <math.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
    //gets user input
    string input = get_string("Text: ");
    //counter for the number of letters
    int numLetters = 0;

    //looks at each character in the string
    for(int i = 0, n = strlen(input); i < n; i++)
    {
        //checks to see if the characeter is in the alphabet
        if(input[isalpha(i)])
        {
            //add to the number of letters in the string
            numLetters++;
        }


    }
    printf("letter(s) %i", numLetters);
    printf("\n");


}

Upvotes: 0

Views: 2614

Answers (2)

Lost in code
Lost in code

Reputation: 313

The mistake is in your if statement, the one inside the loop. It should be:

if (isalpha(input[i]) != 0)
{
  numLetters++;
}

I added the

!= 0

part because 'isalpha' returns a positive integer if it is an alphabetical character, but returns zero if it's not. I hope you found this useful.

Upvotes: 0

vmt
vmt

Reputation: 860

The following if-statement in your loop:

if(input[isalpha(i)])

will use the result of isalpha(i) as an index into the input array, and evaluate its value. Chances are, instead you would like to evaluate the result of the function isalpha() called with the ith character in the string, i.e.

if(isalpha(input[i]))

Upvotes: 4

Related Questions