gpt4 book ai didi

c - 如何像strncat一样使用snprintf?

转载 作者:行者123 更新时间:2023-11-30 14:32:41 24 4
gpt4 key购买 nike

char src1[4+1];
char src2[4+1];
char target[4+1];

strncpy(src1, "1234", sizeof(src1));
strncpy(src2, "ABCD", sizeof(src2));

snprintf(target, sizeof(target), "%3s%1s", src1, src2);
target[4] = '\0';

printf("result: %s\n", target);

结果是“1234”,但我想制作“123A”。

strncpy(src1, "1234", sizeof(src1));
strncpy(src2, "ABCD", sizeof(src2));

strncpy(target, src1, 3);
strncat(target+3, src2, 1);
printf("result: %s\n", target);

当我使用 strncat 而不是 snprintf 时,效果很好。

有人可以解释为什么这段代码(snrpintf)的工作方式与我想象的不同吗?

最佳答案

该数量是最少的。

In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

对于%s,您可以使用精度来指定最大值

[An optional precision] gives [...] the maximum number of characters to be printed from a string for s and S conversions.

所以使用

snprintf(target, sizeof(target), "%3.3s%1.1s", src1, src2);

(不需要 target[4] = '\0'; !)

关于c - 如何像strncat一样使用snprintf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59708705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com