While using sprintf like this
sprintf("%.40s",str);
I want to give a value like strlen(str) in place of 40.How do I do that? I tried replacing 40 with strlen(str), doesn't work. Giving a value like
#define len strlen(str)
and using %.len doesnt work either since %.len is used in " ".
Use *
character.
sprintf(/* ... */, "%.*s", (int) strlen(str), str);
If you use C99, snprintf
can also be suitable.
man printf (3)
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
As GajananH points out this is a pointless endevor:
For strlen
to work, str
must be NULL terminated.
If str
is NULL terminated then:
sprintf(str2, "%.*s", strlen(str), str);
Is just an over complication of:
sprintf(str2, "%s", str);
Which itself is just an over complication of:
strcpy(str2, str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With