首页 > 解决方案 > 实施 isalpha 时遇到问题

问题描述

我一直在研究 CS50 中的可读性问题。第一步是创建一种只计算字母字符的方法。它建议使用该isalpha功能,但并没有真正包括如何实现它的说明。

下面是我的代码,它成功地计算了总字母字符,但未能过滤掉标点符号、空格和整数。

谁能指出我一个更好的方向来实现isalpha它以使其发挥作用?

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

标签: ccs50isalpha

解决方案


#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;
}

推荐阅读