如何解决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
系列函数)的参数是 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。