c - 指针字符数组可以工作,但打印时输出错误的字符

标签 c arrays pointers character

好吧,现在这对于我让这个程序运行的目标来说并不是必需的,但我不明白为什么它会将奇怪的字符存储到数组中,而不是在终端中输入的字符。

这是我运行程序时得到的结果...

输入一条消息:他像魔鬼一样生活,是吗?

HE  ( ╠ ( ═▓!u ·ñΣ■   jX

回文

进程返回 0 (0x0) 执行时间:21.120 s 按任意键继续。

<小时/>

输入消息:女士,我是 Adam。

女士,╠ ( ═▓!u┴:»

不是回文

进程返回 0 (0x0) 执行时间:9.039 s 按任意键继续。

如您所见,它有效 ^....

    // Chapter 12 Programming Project #2

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

    #define N 50

    bool chk_msg(char message[],char *j);

    int main(void)
    {
        char msg[N], *p;
        int chk = 0;

        printf("Enter a message: ");
        for (p = &msg[0]; p < &msg[N];) {
            *p = toupper(getchar());
            if (((int)*p >= 65) && ((int)*p <= 90)) {
                p++;
            } else if (*p == '\n')
                break;
            printf("%c", msg[chk++]);
        }
        printf("\n");

        if (chk_msg(msg, p))
            printf("Palindrome\n\n");
        else
            printf("Not a palindrome\n\n");

        return 0;
    }

    bool chk_msg(char msg[], char *j)
    {
        char *i;
        bool palindrome = true;

        for (i = &msg[0], j--; i < &msg[N]; i++, j--) {
            if (i == j)
                break;
            else if (*i != *j)
                palindrome = false;
        }

        return palindrome;
    }

最佳答案

您正在使用以下条件验证输入字符

if (((int)*p >= 65) && ((int)*p <= 90))

但在此检查中,您仅允许使用字母表 (ASCII 65 - 90),但在输入中您还输入空格 (ASCII 0x20)。这就是你的逻辑出错并且输出中出现垃圾的原因。

如果您的输入中还需要空格,请按如下方式更改条件检查,

if ((((int)*p >= 65) && ((int)*p <= 90)) || ((int)*p == 20))

那么一切都应该没问题。

关于c - 指针字符数组可以工作,但打印时输出错误的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23650173/

相关文章:

C lang "filter map"实现与免费

python - 将二维数组中任意行的值赋给 nans

C数组地址混淆

delphi - 在变体中保存指针的地址并访问它

c - 在C中,有没有更好的方法来计算不确定性值?

c - 如何在c中的链表中实现队列?

c - 如何在Linux中编译静态库?

c - 数组中的元素太多!

c - 它们是否不同 : converting type of pointer then get data AND getting data of pointer then convert datatype

c - C 中指针语法的初学者