Two possibilities of fixing format problem, which is better?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Oct 22 17:12:53 UTC 2019


On Tue, Oct 22, 2019 at 04:34:52PM +0000, berni44 via Digitalmars-d wrote:
[...]
> import std.stdio;
> 
> int[] a = [1,23,-456];
> writeln(format("%20s",a));
> writeln(format("[%(%20s%|, %)]",a));
> 
> produces:
> 
> [                   1,                   23,                 -456]
> [                   1,                   23,                 -456]
> 
> but IMHO the first line should be:
> 
>        [1, 23, -456]
> 
> This is in accordance with the current Phobos spec and some printf
> spec I found in the internet. Should this be corrected?

IMO, yes.  When you write "%20s" you're essentially saying "format the
next argument as a string with width 20". It's unexpected behaviour for
the width to suddenly apply to elements within the object as opposed to
the object itself. If somebody wants the 20 to apply to each element
instead, then he should write the second format string as you showed
above.


> Similar:
> 
> import std.stdio;
> 
> char[] a = ['a','b','c'];
> writeln(format("%20s",a));
> writeln(format("[%(%20s%|, %)]",a));
> 
> produces:
> 
>                  abc
> ['a', 'b', 'c']
> 
> And:
> 
> import std.stdio;
> 
> String[] a = ["a","b","c"];
> writeln(format("%20s",a));
> writeln(format("[%(%20s%|, %)]",a));
> 
> produces:
> 
> ["a", "b", "c"]
> ["a", "b", "c"]
> 
> So my question remains: What is considered correct behaviour here?

IMO the 20 should apply to whatever object the next argument is *as a
whole*, since that's the most useful and expected behaviour. It's
unexpected for "%20s" to apply the 20 width to the entire object when
the argument is a string, but suddenly changes to 20 width *per element*
when the argument is an array that isn't a string.


T

-- 
There are three kinds of people in the world: those who can count, and those who can't.


More information about the Digitalmars-d mailing list