在 CI 中执行以下操作时会发生什么:
char buf[50]="";
c = fgetc(file);
buf[strlen(buf)] = c+'\0';
buf[0] = '\0';
我在循环中使用了一些这段代码,并在 buf 中找到旧值我只想将 c 添加到 buf
我知道我可以做到:
char s=[5];
s[0]=c;
s[1]='\0';
strcat(buf, s);
将字符添加到 buf,但我想知道为什么上面的代码不起作用。
在 CI 中执行以下操作时会发生什么:
char buf[50]="";
c = fgetc(file);
buf[strlen(buf)] = c+'\0';
buf[0] = '\0';
我在循环中使用了一些这段代码,并在 buf 中找到旧值我只想将 c 添加到 buf
我知道我可以做到:
char s=[5];
s[0]=c;
s[1]='\0';
strcat(buf, s);
将字符添加到 buf,但我想知道为什么上面的代码不起作用。
为什么它会起作用?
char buf[50]="";
将第一个元素初始化为'\0'
,strlen(buf)
因此0
.
'\0'
是一种花哨的说法0
,所以c+'\0'==c
,所以你正在做的是
buf[0]=c;
buf[0]=0;
这没有任何意义。
最后两行的复合效果
char buf[50]="";
c = fgetc(file);
buf[strlen(buf)] = c+'\0';
buf[0] = '\0';
是无操作的。
这个:
buf[strlen(buf)] = c+'\0';
将导致:
buf[strlen(buf)] = c;
意味着不会发生任何添加。
因此,将会发生的是:
buf[0] = c;
因为strlen(buf)
是0。
这个:
buf[0] = '\0';
在字符串的开头放置一个空终止符,覆盖c
(您刚刚分配给buf[0]
)。结果它重置buf
为""
.
buf[strlen(buf)] = c+'\0';
可能他们想要
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;
}