由putchar在最后一个字符后打印的垃圾

问题描述 投票:0回答:1

我的putchar()函数在总和之后返回垃圾。

这是我的代码片段:

scanf("%d", & keys);
getchar();
while ((c = getchar()) != EOF)
{
    c = c + keys;
    putchar(c);
}
puts("");
c ansi
1个回答
0
投票

如果我明白你要去哪里,你的问题(最后的有趣人物)是由于你加入c = c + keys;导致字符值大于126(例如'~'字符)。例如,如果你的keys大于4并输入'z',那么你得到的c + keys超出了ASCII字符的有效范围。见ASCII Table and Description

根据你想要做的事情,你可以简单地使用%(modulo)来确保在调用putchar()之前总是有一个有效的ASCII字符。就像是:

    while ((c = getchar()) != EOF) {
        c = (c + keys) % ('~' - ' ' + 1) + ' '; /* use modulo to ensure ASCII */
        putchar (c);
    }

(注意:'~' - ' ' + 1只是ASCII值的可打印范围 - 95 chars - 感谢Roland)

把一个简短的示例程序放在一个看起来就像你要去的地方,你可以这样做:

#include <stdio.h>

/* simple helper function to remove to end of line */
void empty_line (void)
{
    int c = getchar();

    while (c != '\n' && c != EOF)
        c = getchar();
}

int main (void) {

    int c, keys;

    if (scanf("%d", & keys) != 1 || keys < 0) { /* Validate EVERY Input! */
        fputs ("error: invalid or negative integer input.\n", stderr);
        return 1;
    }
    empty_line();

    while ((c = getchar()) != EOF) {
        c = (c + keys) % ('~' - ' ' + 1) + ' '; /* use modulo to ensure ASCII */
        putchar (c);
    }
    putchar ('\n');     /* not puts, you need 1-char, not string */
}

(注意:您必须验证每个输入,特别是在使用scanf执行到int的转换时 - 或任何其他类型)

示例使用/输出

$ ./bin/putcharmod
33
My dog has zero fleas, my cat has none :)
/[aFQIaJCUa\GTQaHNGCUmaO[aECVaJCUaPQPGa{jK

在上面,尽管有keys = 33,输入'z'导致没有有趣的字符,因为总c + keys减少到可打印的字符范围内。

当然,调整方案以满足您的最终目标,但无论如何,如果您使用stdout输出到putchar(),您将需要做类似的事情以确保您输出的内容是可打印的。

如果您有其他问题,请与我们联系。

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