C程序计算一个单词中的字母数给出错误

问题描述

代码如下:

#include<stdio.h>

int main()
{
    int alpha = 0,input;

    while((input = getchar() != EOF))
    {
        if(isalpha(input))
            alpha++;
    }

    printf("Num of alpha is %d",alpha);
    return(0);
}

我收到错误

isalpha 未在此范围内声明

在 DevC++ 编译器上编译时。

解决方法

isalpha()ctype.h

中声明

知道即使 isalpha(以及所有 isxxx 系列函数)的参数是 intthe behavior is undefined if the argument is negative. 所以如果你是在 char 签名为默认值的机器上,除非您先进行转换,否则您可能会遇到麻烦。像这样:

char c;
// Some code
if(isalpha((unsigned char) c)) {

总是为这些函数强制转换是一个好习惯。但是,不要使用强制转换作为消除警告的 g​​oto。它可以轻松隐藏错误。在大多数需要强制转换的情况下,您的代码在其他方面是错误的。 Rant about casting

这些函数(以及许多其他返回 int 作为布尔值的 C 函数)的另一个缺陷是它们需要在 false 时返回零,但在 true 时允许返回任何非零值。所以像这样的检查完全是胡说八道:

if( isalpha(c) == 1 ) 

改为执行以下任一操作:

if( isalpha(c) != 0 )   // If not zero
if( isalpha(c) )        // Use directly as Boolean (recommended)
if( !! isalpha(c) == 1) // Double negation turns non zero to 1

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...