简体   繁体   中英

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

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.

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

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. ie:

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

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

Output:

hellthere

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM