首页 > 解决方案 > 在 while 循环中同时使用 isalpha 和 toupper 会给出“索引超出范围”

问题描述

这是给出错误的代码"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']++ ;
    }

它的行为如愿,错误消失了。我在导致错误的第一个错误中做错了什么?

标签: carrayswhile-loopindexoutofboundsexception

解决方案


The error message says index -65, so x-'A' in a[x-'A'] must be -65. The ASCII value of 'A' is 65, giving x-65 = -65, which resolves as x = 0.

Why is x = 0?

Because x is the result of isalpha, which returns a boolean value. In particular, it returns 0 for false.

Also, it makes no sense to compare this boolean value to '\n'.

Did you mean

while (isalpha(x = toupper(getchar())))

?

Note that your code doesn't handle EOF correctly, though. EOF is not a char, which is why getchar returns int. Assigning its result to x loses information.


推荐阅读