简体   繁体   English

指针字符数组有效,但是在打印时输出错误的字符

[英]Pointer character array works, but when printed outputs the wrong characters

Ok now this isn't imperative for my goal in getting this program to work, but I don't understand why it's storing strange characters into the array in place of the characters typed into the terminal. 好了,这对于实现该程序的目标并不是强制性的,但是我不明白为什么它会将奇怪的字符存储到数组中来代替在终端中键入的字符。

Here is what I get when I run the program... 这是我运行程序时得到的...

Enter a message: He lived as a devil, eh? 输入一条消息:他过着魔鬼的生活,是吗?

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

Palindrome 回文

Process returned 0 (0x0) execution time : 21.120 s Press any key to continue. 进程返回0(0x0)执行时间:21.120 s按任意键继续。


Enter a message: Madam, I am Adam. 输入一条消息:女士,我是亚当。

MADAM,╠ ( ═▓!u┴:» MADAM,╠(═▓!u┴:»

Not a palindrome 不是回文

Process returned 0 (0x0) execution time : 9.039 s Press any key to continue. 进程返回0(0x0)执行时间:9.039 s按任意键继续。

As you can see it works ^.... 如您所见,它起作用了^...。

    // 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;
    }

You are validating the input characters with the following condition 您正在验证具有以下条件的输入字符

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

But in this check you are allowing only alphabets (ASCII 65 - 90), but in the input you are inputting also spaces (ASCII 0x20). 但是在此检查中,您只允许使用字母(ASCII 65-90),但在输入中您还输入空格(ASCII 0x20)。 This is the reason your logic goes wrong and you get garbage in the output. 这就是您的逻辑出错并在输出中产生垃圾的原因。

If you also need spaces in your input change the condition check as follows, 如果您在输入中还需要空格,请按如下所示更改条件检查,

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

Then everything should be fine. 然后,一切都会好起来的。

A string in C ends with '\\0' , the so called terminator. C中的字符串以'\\0'结尾,即所谓的终结符。 You never add one, so your string just runs off into random memory. 您永远不会添加一个,因此您的字符串只会耗尽到随机内存中。 Your code gets undefined behavior when dealing with that broken string. 处理该损坏的字符串时,您的代码将获得未定义的行为。

Also, you should never hardcode ASCII values like that, use eg isalpha() to filter. 另外,您绝对不要像这样对ASCII值进行硬编码,例如使用isalpha()进行过滤。

Your message reading function is a big mess: 您的消息阅读功能非常混乱:

This works: 这有效:

for (p = &msg[0]; p < &msg[N];) {
    char c = toupper(getchar());

    if ((c >= 'A') && (c <= 'Z')) {  // filter out anything not between A and Z
        *p++ = c;
        printf("%c", c);
    }
    else if (c == '\n') {
        *p = 0 ;              // put the zero terminator
        break;
    }
}

EDIT: 编辑:

And your chk_msg is also wrong and overly complicated. 而且您的chk_msg也是错误的并且过于复杂。

This is a corrected version: 这是一个更正的版本:

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

    for (i = &msg[0], j--; i < j; i++, j--) {
       if (*i != *j) {
         return true ;
       }
    }

    return false;
}

First, you can use isupper or isalpha to check for upper case or alphabetic characters. 首先,您可以使用isupperisalpha检查大写或字母字符。

You get strange characters, because you printf("%c", msg[chk++]); 您会得到奇怪的字符,因为您是printf("%c", msg[chk++]); . You increase chk , no matter if you inserted a character before. 增加chk ,无论之前是否插入字符。

When you move printf inside the first if , it should work as expected 当您在第一个if移动printf if ,它应该可以正常工作

if (isupper(*p)) {
    p++;
    printf("%c", msg[chk++]);
} else if (*p == '\n')
    break;

A small optimization: You can move the comparison in chk_msg to the for exit condition 一个小的优化:您可以将chk_msg的比较chk_msg for退出条件

for (i = msg, j--; i < j; i++, j--) {
    if (*i != *j)
        palindrome = false;
}

Thanks again everyone for your input and help 再次感谢大家的投入和帮助

    // 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 (isalpha(*p)) {
                p++;
                printf("%c", msg[chk++]);
            } else if (*p == '\n') {
                break;
            }
        }
        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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM