Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf usage with %.s

Tags:

c

printf

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 " ".

like image 304
Iceman Avatar asked Dec 05 '22 13:12

Iceman


2 Answers

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.

like image 159
md5 Avatar answered Dec 23 '22 03:12

md5


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);
like image 32
weston Avatar answered Dec 23 '22 03:12

weston