sprintf writing a blank string when used with %*.s format specifier

3.2k views Asked by At

I have an sprintf as follows -

sprintf (output,"%.*s%s%s%s",length,Str1,Str2,Str3,Str4);

All the strings contain valid data and the length parameter as well is correct. Yet, output remains emtpty after this sprintf.

If I replace %.*s with %s and remove the length parameter, it works perfectly fine.

2

There are 2 answers

0
Himanshu On

Try This

Change

sprintf (output,"%*.s%s%s%s",length,Str1,Str2,Str3,Str4);

To

sprintf (output,"%.*s%s%s%s",length,Str1,Str2,Str3,Str4);
                  ^^
0
AudioBubble On

The reason why nothing is being output is because if you omit the trailing digit or star after the dot, the precision is taken to be zero. %*. modifies the width not the precision. Instead, you want %.*. Note that this only applies to the conversion specifier it is a part of. i.e:

char output[100];
char str1[] = "hello";
char str2[] = "there";
int length = 4;

sprintf(output, "%.*s%s", length, str1, str2);
printf("%s", output);

Output:

hellthere