Trouble implementing isalpha

2020-05-04 04:41发布

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");
}

标签: c cs50 isalpha
1条回答
The star\"
2楼-- · 2020-05-04 05:30
#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;
}
查看更多
登录 后发表回答