【问题标题】:Why when my input is 8 or more characters long, symbols appear after printing the 8 character?为什么当我的输入长度为 8 个或更多字符时,打印 8 个字符后出现符号?
【发布时间】:2019-08-31 18:02:12
【问题描述】:

当我打印 8 个或更多字符时,符号总是在第 8 个字符之后打印。有谁知道代码有什么问题,我该如何解决?

我尝试过使用不同数量的字符,但总是在超过 8 或 8 个时发生。

#include <stdio.h>

int main() {
    char ch = 0;
    char temp[100];
    int i = 0;
    while (scanf("%c", &ch) == 1) {
        if (ch != '\n') {
            temp[i] = ch;
            printf("%s", temp);
            i++;
        }
    }
    return 0;
}

我的预期结果是

1   12  123 123412345123456123456712345678

我的实际输出是

1   12  123 123412345123456123456712345678xxx

x 代表符号

【问题讨论】:

  • 你不会空终止字符串。任何事情都可能发生,因为它会调用未定义的行为

标签: c printing


【解决方案1】:

在输出中出现有趣字符的原因是 temp 数组不是正确的 C 字符串,因为它未初始化,因此在使用 @987654324 设置的 ith 条目之后不一定有空字节 '\0' @。

有不同的方法来解决这个问题:

  • 你可以这样初始化tempchar temp[100] = { 0 };

  • 您可以在循环中将temp[i+1] 的字节设置为'\0'

还要注意,预期的输出不是1 12 123 123412345123456123456712345678,而是112123123412345123456123456712345678,因为您没有在字符串之间输出分隔符。在单独的行上输出字符串会更容易混淆。

最后,scanf() 在用户输入换行符之前不会返回,因为终端驱动程序和标准输入流执行了缓冲。

这是修改后的版本:

#include <stdio.h>

int main() {
    char ch;
    char temp[100];
    size_t i = 0;
    while (scanf("%c", &ch) == 1 && i + 2 < sizeof(temp)) {
        if (ch != '\n') {
            temp[i] = ch;
            temp[i + 1] = '\0';
            printf("%s", temp);
            i++;
        }
    }
    return 0;
}

【讨论】:

  • 请注意,这将输入双倍空格,为输入中的每一个打印两个换行符。原版似乎不想这样做。不要在字符串中添加换行符,或者不要在 printf() 的格式字符串中包含换行符,或者使用 fputs(temp, stdout)(但不是 puts(temp))。
  • 我建议使用第一个版本;从长远来看,它可能会更有效率。
  • Corner ,请注意 sizeof(temp) - 2 是一个 unsigned 减法,当 sizeof temp == 1 导致循环中的 UB 时具有环绕效果。建议i + 2 &lt; sizeof(temp)
【解决方案2】:

@chqrlie 很好地解释并提供了 2 个替代方案。

第三种选择:更改格式

printf("%s\n", temp) 期望 temp 是一个字符串。在 C 中,string 有一个 null 字符,否则它不是 string

代码无法确保temp[] 中的'\0'。结果是未定义的行为 (UB)。

代码可以使用 precision 来限制使用"%s" 打印的字符数。

    // printf("%s", temp);
    printf("%.*s", (int)i, temp);

"%.*s", (int)i, temp 将打印最多i 个字符或最多'\0' - 以先到者为准。 i 被强制转换为 (int),因为 printf 需要一个 int 来表示在 s 之前由 .* 指定的额外参数给出的 precision

int main(void) {
    char temp[100];
    size_t i = 0;
    while (i < sizeof temp && scanf("%c", &temp[i]) == 1 && temp[i] != '\n') {
        i++;
    }
    printf("<%.*s>\n", (int)i, temp);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多