A possible feature request: Make writef with %s call to!string for char* parameters

Andrej Mitrovic andrej.mitrovich at gmail.com
Mon Jul 11 13:37:12 PDT 2011


import std.stdio;
import std.string;

void main()
{
    char* foo = "foo\0".dup.ptr;
    writefln("Foo: %s", foo);
}

This will write the address of foo. Often when you link with C code
you have C structures such as this:
struct Info
{
    char* name;
    char* info;
}

I think it would be convenient if writef would call to!string for
char* parameters behind the scenes if %s is the format specifier.

I mean yes, you can use to!string in your code, or you can write D
classes that wrap C libraries, but when you're *testing* D code ported
from C it would be so much more convenient if you can pass a char* to
writef() and use %s to treat it as a C string without having to go
through the trouble of writing to!string everywhere.

Besides, writef is probably used the most with quick logging and
debugging, so I think it makes sense to make it more versatile.

And if you really want the address of a char*, there's always the %X
format specifier:
writefln("Foo: %X", foo);

Or you could use writeln directly: writeln(foo); Although that would
make things a little awkward since writeln would then behave
differently than the writefln("%s") equivalent.. I'm not sure about
this case.

I know this feature would save *me* a ton of time when testing and
debugging ported code. Most C code already uses %s with printf, and to
use that code in D it would be a simple matter of doing a
search&replace of print with writef. Otherwise currently I have to
manually hunt & peck for every printf call and add to!string
everywhere.

But what do others  think?


More information about the Digitalmars-d-learn mailing list