将带有空终止符的char添加到C中的字符串

Adding char with null terminator to string in C

当我在 C 中执行类似以下操作时会发生什么:

char buf[50]="";
c = fgetc(file);
buf[strlen(buf)] = c+'[=10=]';
buf[0] = '[=10=]';

我在循环中使用了这段代码,并在 buf 中找到了旧值 我只想将 c 添加到 buf

我知道我可以做到:

char s=[5];
s[0]=c;
s[1]='[=11=]';
strcat(buf, s);

将 char 添加到 buf,但我想知道为什么上面的代码不起作用。

这个:

buf[strlen(buf)] = c+'[=10=]';

将导致:

buf[strlen(buf)] = c;

表示不会进行加法。

因此,会发生的事情是:

buf[0] = c;

因为 strlen(buf) 是 0。


这个:

buf[0] = '[=13=]';

在字符串的开头放置一个空终止符,覆盖 c(您刚刚分配给 buf[0])。结果它将 buf 重置为 "".

为什么会起作用?

char buf[50]=""; 将第一个元素初始化为 '[=13=]',因此 strlen(buf)0'[=13=]' 是一种花哨的说法 0,所以 c+'[=18=]'==c,所以你正在做的是

buf[0]=c;
buf[0]=0;

这没有任何意义。

最后两行的复合效果

char buf[50]="";
c = fgetc(file);
buf[strlen(buf)] = c+'[=11=]';
buf[0] = '[=11=]';

是空操作。

 buf[strlen(buf)] = c+'[=10=]';

可能他们想要

buf[length_of_the_string_stored_in_the_buf_table] = c;
buf[length_of_the_string_stored_in_the_buf_table + 1] = 0;

同样删除最后一个字符

char *delchar(char *s)
{
    int len = strlen(s);
    if (len)
    {
        s[len - 1] = 0;
    }
    return s;
}