C可以假定我要存储哪个数组的字符吗?

问题描述 投票:-4回答:2

我正在编写检查数组是否为回文的代码:

写一个程序,读取消息,然后检查它是否是回文(消息中的字母从左到右与从右到左相同):

输入信息:他过着魔鬼的生活,是吗?回文

[输入消息:女士,我是亚当。不是回文

当我输入He lived as a devil, eh?后,它给我输出Not a palindrome,但实际输出应为palindrome

下面的代码是到目前为止我尝试过的。

#include <stdio.h>
#include <ctype.h> 

#define MAX_LEN 100

int main(void) {

    char message[MAX_LEN];
    char c, *p = message, *q;

    printf("Enter a message: ");

    while ((c = toupper(getchar())) != '\n' & p < message + MAX_LEN) {
        if (isalpha(c))
            *p++ = c;
    }
    p--;

    for (q = message; q < p; q++, p--) {
        if (*p != *q) {
            printf("Not a palindrome\n");
            return 0;
        }
    }
    printf("Palindrome\n");
    return 0;
}
c arrays pointers c-strings palindrome
2个回答
1
投票

检查回文之前,您必须删除空白和标点符号。例如,如果您使用civic?,则不是因为?而回文。另一方面,如果使用civ ic,则不是空白,因为空白。那里


0
投票

对于初学者,您应将变量c声明为类型int。用户可以中断输入过程,在这种情况下,函数getchar返回整数值EOF,您应该检查是否发生了这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.