jacob said:
Has anyone here any information about how arrays can be
formatted with printf?
I mean something besides the usual formatting of each element
in a loop. I remember that Trio printf had some extensions but
I do not recall exactly if they were meant for arrays.
The Trio had a lot of interesting extensions via its trio_printf family
of functions, you are probably referring to the trio_printfv (the v for
vector I suppose) function which takes an array of pointers to void as
its second argument. For example, "trio_printfv("%d %d %f\n", vp);"
would expect vp to be the address of the first void pointer in an array
of 3 void pointers that could be converted to pointers to int, int, and
double respectively. This doesn't sound like it accomplishes what you
are looking for, I haven't ever seen anything that does.
Here is what I came up with (I haven't put much thought into this, it
should probably be considered a testament to why this isn't a good
idea):
Example 1:
my_printf("%[10]d\n", int_array);
This would print out 10 integers from int_array, I use the the brackets
to indicate an array is the argument and specify the number of items
from the array to print. In this example, the integers would be
seperated by a single space, this would be the default.
Example 2:
my_printf("%[10%c]d\n", int_array, ",");
In this example we explicitly specify the delimiter by using a second
conversion specifier inside the brackets after the number of array
members, in this case 'c' for character. The argument corresponding to
the delimiter follows the array argument.
Example 3:
my_printf("%[10%s]d\n", int_array, "my delimiter string");
Same as above but specify a string as the delimiter.
Of course you can use field width, precision, etc. with this format:
my_printf("%6.2[10]f\n", double_array);
If this is not enough control over delimiter choices, you can specify a
list of delimiters as well:
Example 4:
my_printf("%[10%[5]c]d\n", (int []){1,2,3,4,5,6,7,8,9,10}, "abcde");
Specifies that we want to print an array of 10 integers delimited by an
array of 5 characters and that we want to iterate through the
characters as delimeters wrapping back to the first one after the last
one is used.
This would of course print:
1a2b3c4d5e6a7b8c9d10
Notice that there is no delimiter following the last member printed.
We won't allow any further nesting of conversion specifiers for
simplicity sake but we should allow multiple non-nesting conversion
specifiers in the delimeter string:
my_printf("%[3%c%[2]c]d\n", (int []){1,2,3}, "-", "*/");
would print:
1-*2-/3
Of course, you could also provide a pointer to a function that is
called after printing each value to return the delimiter for that
value, I'll spare you the semantics of that one.
I'd be interested to know what you come up with.
Robert Gamble