hackish writefln? and

david ta-nospam-zz at gmx.at
Sat Apr 28 13:38:42 PDT 2007


Frits van Bommel schrieb:
> david wrote:
>> Hello all!
>>
>> Is
>>     writefln( (i<10?" ":"") ~ "%d: %s", i, v);
>>
>> supposed to work, according to the specs?
>> Just looked at them, but couldn't quiet get it.
> 
> Yes, that should be fine (assuming i is some form of integer).
> 
>> But nevertheless it *does* work,
>> no compile/runtime error and it acts
>> also in the expected way.
>>
>> BUT: I just came back from hunting (bugs),
>> and you get an error if you write the above code
>> in a file, read it in using std.file & std.stream,
>> and writefln it back to the console:
>>
>> *** bugtest.txt
>> writefln( (i<10?" ":"") ~ "%d: %s", i, v);
>>
>> *** bugtest.d
>> import std.file, std.stream, std.stdio;
>> void main()
>> {
>>     File file = new File;
>>     file.open("bugtest.txt");
>>     char[] line;
>>     line = file.readLine();
>>     file.close();
>>     writefln(line);        // here we get an error
>> }
> 
> That's a different matter entirely. String arguments to writef and 
> friends are by default treated as format strings. Since the string you 
> provide contains %d and %s, it expects two additional arguments. Since 
> none are provided it throws an exception. Change the last line to
> ---
>     writefln("%s", line);
> ---
> to write out the exact contents of the string.
> 
> Stuff like this is why we *really* need non-formatting write functions 
> :(...

Thanks a lot for the explanation, now it is clear (and works).
Althoug I guess this could pose a risk for bugs in other people's code,
since the code itself works and the bug only pops up on very special
input data occasions. (glad I'm enlightened now ^_^)

david


More information about the Digitalmars-d-learn mailing list