Using sprintf with% .s

When using sprintf like this

sprintf("%.40s",str); 

I want to give a value like strlen (str) instead of 40. How to do this? I tried replacing 40 strlen (str), not working. Attaching meaning, for example

 #define len strlen(str) 

and using% .len does not work, since% .len is used in "".

+4
source share
3 answers

Use the * symbol.

 sprintf(/* ... */, "%.*s", (int) strlen(str), str); 

If you are using C99, snprintf may also be suitable.

man printf (3)
The width is not indicated in the format string, but as an additional argument of an integer value preceding the argument to be formatted.

+9
source

As GajananH points out, this is a meaningless endevor:

For strlen to work, str must be NULL terminated.

If str is NULL, then:

 sprintf(str2, "%.*s", strlen(str), str); 

This is just a complication:

 sprintf(str2, "%s", str); 

Which in itself is more complex:

 strcpy(str2, str); 
+4
source

I do not really understand the meaning of using strlen() . If strlen() works for you, that means your string is NULL terminated, and if the string is NULL terminated, there is no real use of putting the number for %s (unless you are trying to use a number smaller than the length of the string.

If your line is not NULL terminated then strlen() will return the wrong value, and using this parameter for %s will not help.

Instead, I suggest you use strnlen () with a string length limit and use the return value for %s .

+2
source

Source: https://habr.com/ru/post/1444798/


All Articles