views:

73

answers:

3

Looking at the information under the heading "Precision can be omitted or be any of:".

The example: printf("%.*s", 3, "abcdef"); works, outputting:abc (truncating the rest of the string.)

Now, I would like to have a string with multiple parameters formatted (truncated):

printf("%.*s, %.*s", 3, 3, "abcdef", "xyz123");

but the program crashes.

What is the correct syntax?

Thank You.

+5  A: 

Maybe you should change order?

printf("%.*s, %.*s", 3, "abcdef", 3, "xyz123");

By the way you can hardcode precision if you don't need it as a variable:

printf("%.3s, %.3s", "abcdef", "xyz123");

(Stephen Canon kindly corrected the typo)

Jack
How did this get 5 upvotes? It doesn't work. It gives warnings when compiling, and segfaults when it runs. The hardcoded one doesn't work either.
Carl Norum
Jack, I edited your format strings so that this compiles and works properly.
Stephen Canon
Thanks, it was a typo based just to have quickly copied and pasted the other code, sorry :)
Jack
+2  A: 

You want to do it like this:

printf("%.*s, %.*s", 3, "abcdef", 3, "xyz123");

The format arguments should be in the same order as the format specifiers.

mipadi
That doesn't work; there are still two format strings.
Carl Norum
Fixed (I had copied the line from the original post, didn't notice the improperly-placed double quotes).
mipadi
+1  A: 
printf("%.*s, %.*s",3,"abcdef",3,"xyz123");
mingos