Trouble implementing isalpha

ε祈祈猫儿з 提交于 2020-06-09 05:24:14

问题


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

回答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;
}


来源:https://stackoverflow.com/questions/61399924/trouble-implementing-isalpha

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!