问题描述
代码如下:
#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
系列函数)的参数是 int
,the behavior is undefined if the argument is negative. 所以如果你是在 char
签名为默认值的机器上,除非您先进行转换,否则您可能会遇到麻烦。像这样:
char c;
// Some code
if(isalpha((unsigned char) c)) {
总是为这些函数强制转换是一个好习惯。但是,不要使用强制转换作为消除警告的 goto。它可以轻松隐藏错误。在大多数需要强制转换的情况下,您的代码在其他方面是错误的。 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