这是给出错误的代码 "index -65 out of bounds for type 'int [26]'"
char x;
int a[26] = {0};
printf("Enter first word: ");
while ((x=(isalpha(toupper(getchar())))) != '\n')
{
a[x-'A']++;
}
而如果我将其更改为此
char x;
int a[26] = {0};
printf("Enter first word: ");
while ((x=((toupper(getchar()))) != '\n')
if (isalpha(x))
{
a[x-'A']++ ;
}
它表现得很理想,错误消失了。在导致错误的第一个错误中我做错了什么?
错误消息显示index -65
,因此x-'A'
ina[x-'A']
必须为-65。的ASCII值为'A'
65(给定)x-65 = -65
,其解析为x = 0
。
为什么x = 0
呢?
因为x
是的结果isalpha
,所以返回布尔值。特别是,它返回0
的错误。
此外,将此布尔值与进行比较也没有意义'\n'
。
你的意思是
while (isalpha(x = toupper(getchar())))
?
请注意,您的代码无法EOF
正确处理。EOF
不是char
,这就是为什么要getchar
返回int
。将其结果分配给将x
丢失信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句