0

I've been working on the readability problem in CS50. The first step is to create a way to count only the alphabetical characters. It suggests to use the isalpha function, but doesn't really include directions on how to implement it.

Below is my code which succeeds in counting total alphabetical characters, but fails to filter out punctuation, spaces and integers.

Could anyone point me in a better direction to implement the isalpha so that it functions?

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

int main(void)
{
    string s = get_string ("Text: \n");     // Ask for text

// Loop through the string one character at a time. Count strlen in variable n.
    for (int i = 0, n = strlen(s); i < 1; i++) 

// Count only the alphabetical chars.
    {
        while (isalpha (n)) i++;
        printf ("%i", n );
    }

    printf("\n");
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Are you sure you're supposed to be implementing `isalpha` yourself? The standard library contains its own implementation of it, which you can use since you have `#include `. – Joseph Sible-Reinstate Monica Apr 24 '20 at 02:12
  • No- I am not sure.... I am totally new to this. How would I use the isalpha then if I don't specify it? – Dizzy_Parking Apr 24 '20 at 02:13
  • 1
    You didn't write `printf`, but you call it. `isalpha` is the same way. – Joseph Sible-Reinstate Monica Apr 24 '20 at 02:14
  • I see... So when I delete the while and make that line isalpha (n); i++ I still get the same number. – Dizzy_Parking Apr 24 '20 at 02:19
  • Check what input you are giving to isalpha() and do you really need a while condition there ? – Anirudh Apr 24 '20 at 03:01
  • Does CS50 have a "string" type in the C-language? Standard-C does not have a `string`. – abelenky Apr 24 '20 at 03:09
  • @abelenky — for better or worse (and IMO not for better), CS50 does use a type `string` which is basically `typedef char *string;`. Don't blame the students for that!! – Jonathan Leffler May 03 '20 at 17:20
  • Definitely not blaming the student, was just genuinely curious. And I agree, it is for the worse: an object of type `string` + 1 makes very little sense; an object of type `char*` + 1 is much more useful. The more I learn about CS50, the less I like it. – abelenky May 03 '20 at 21:43

1 Answers1

1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    const char* s = get_string ("Text: \n");
    int count = 0;

    while(*s) count += !!isalpha(*s++);

    printf ("%d\n", count );
    return 0;
}
abelenky
  • 63,815
  • 23
  • 109
  • 159