NotMax
NotMax

Reputation: 3

How to use snprintf like strncat?

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);

Result is "1234" but I wanted to make "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);

When I use strncat instead of snprintf, it works well.

Can someone explain why this code (snrpintf) works differently than I thought?

Upvotes: 0

Views: 162

Answers (1)

ikegami
ikegami

Reputation: 386331

The number is a minimum.

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.

For %s, you can use the precision to specify a maximum

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

So use

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

(No need for the target[4] = '\0'; with this!)

Upvotes: 1

Related Questions