实施isalpha时遇到问题 [英] Trouble implementing isalpha

查看:104
本文介绍了实施isalpha时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究CS50中的可读性问题。第一步是创建一种仅计算字母字符的方法。它建议使用 isalpha 函数,但实际上并未包括实现方法的说明。

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.

有人能指出我一个更好的方向来实现 isalpha 使其起作用吗?

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


推荐答案

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

这篇关于实施isalpha时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆