puts() 输出附加 "time" 字符串

puts() output is appended "time" string

我从非常简单的代码中得到了非常意外的输出

char ch = getchar(), word[100], *p = word;

while (ch != '\n') {
    *(p++) = ch;
    ch = getchar();
}
puts(word);

任何 17 个字符输入的输出都附加了 "time" like

12345678901234567time

如果超过"time"则覆盖

1234567890123456789me

我是不是做错了什么?

puts 需要指向 string 的指针。 string 需要有一个终止符 null character - [=15=] - 以表示字符串结束的位置。

但在你的情况下,你没有在末尾写 [=15=] 来表示字符串到此结束。

您需要做的:

char ch = getchar(), word[100], *p = word;

/* Also check that you are not writing more than 100 chars */
int i = 1;
while(ch != '\n' && i++ < 100){  
    *(p++) = ch; 
    ch = getchar();
}
*p = '[=10=]'; /* write the terminaring null character */
puts(word);

以前,当您不编写终止空字符时,您不能指望打印任何确定的内容。它也可能是 12345678901234567AnyOtherWord 之类的。

您的代码中存在多个问题:

  • 你不会空终止你传递给 puts() 的字符串,调用未定义的行为......在你的情况下,在最后一个从 stdin 在这些之后打印,直到(希望)最终在内存中找到 '[=14=]' 字节。
  • 您从 stdin 中读取了一个字节到 char 变量中:这不允许您检查 EOF,事实上您也不能。
  • 如果您读取一长行,如果 word 数组,您将写入超出末尾的字节,从而调用未定义的行为。如果在从 stdin 读取 '\n' 之前遇到文件末尾,您肯定会写入超出缓冲区末尾的内容...例如,尝试为您的程序提供一个空文件作为输入。

这是更正后的版本:

char word[100];
char *p = word;
int ch;

while ((ch = getchar()) != EOF && ch != '\n') {
    /* check for long line: in this case, we truncate the line */
    if (p < word + sizeof(word) - 1) {
        *p++ = ch;
    }
}
*p = '[=10=]';
puts(word);